Created
March 6, 2019 16:52
-
-
Save pokisin/5201fe8e8e73d676cf056ee06667b6b9 to your computer and use it in GitHub Desktop.
Output Django queryset as JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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