Skip to content

Instantly share code, notes, and snippets.

@pokisin
Created March 6, 2019 16:52
Show Gist options
  • Save pokisin/5201fe8e8e73d676cf056ee06667b6b9 to your computer and use it in GitHub Desktop.
Save pokisin/5201fe8e8e73d676cf056ee06667b6b9 to your computer and use it in GitHub Desktop.
Output Django queryset as JSON
def get_json_list(query_set):
list_objects = []
for obj in query_set:
dict_obj = {}
for field in obj._meta.get_fields():
try:
if field.many_to_many:
dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
continue
dict_obj[field.name] = getattr(obj, field.name)
except AttributeError:
continue
list_objects.append(dict_obj)
return list_objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment