Skip to content

Instantly share code, notes, and snippets.

@justinline
Last active February 22, 2018 14:10
Show Gist options
  • Save justinline/dcf2bfc79693a9a370ea3fec6d46ac7a to your computer and use it in GitHub Desktop.
Save justinline/dcf2bfc79693a9a370ea3fec6d46ac7a to your computer and use it in GitHub Desktop.
import json
from django.core.management.base import BaseCommand, CommandError
from django.apps import apps
class Command(BaseCommand):
help = 'Takes a model argument in the form of app_label.model_name and outputs all fields and values as JSON'
def add_arguments(self, parser):
parser.add_argument('model', nargs="1", help='A model argument in the form of app_label.model_name')
def handle(self, *args, **options):
# Get Model class and fields by input. Queries all instances of that model.
app_label, model_name = options['model'].split('.')
model_class = apps.get_model(app_label, model_name)
model_fields = model_class._meta.get_fields()
model_instances = model_class.objects.all()
output = []
for instance in model_instances:
# Generate new dict for fields and values of each instance
d = {}
for field in model_fields:
# Store instance attributes
key = field.name
try:
value = getattr(instance, field.name)
except AttributeError:
print("Error retrieving attribute for ", field.name, " of ", instance)
d[key] = value
output.append(d)
return json.dumps(output)
# --- Sample Outputs ---
$ python manage.py modeltojson livetest.TestModel
[{"field2": false, "id": 1, "field3": "Hello", "field1": 1}, {"field2": true, "id": 2, "field3": "Hello", "field1": 1}]
$ python manage.py modeltojson livetest.TestModel2
[{"id": 1, "second_field": true, "third_field": "hello", "first_field": 1}]
$ python manage.py modeltojson testapp.SecondTest
[
{"field3": false, "id": 1, "field1": "hello, world", "field2": 0},
{"field3": false, "id": 2, "field1": "hello, world", "field2": 0},
{"field3": false, "id": 3, "field1": "This is a charfield", "field2": 0}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment