Created
June 26, 2015 00:59
-
-
Save z4none/0e9a26ca6ebb39627b59 to your computer and use it in GitHub Desktop.
django model to dict (with related model)
This file contains hidden or 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
| from django.forms.models import model_to_dict | |
| authors = [] | |
| for author in Author.objects.prefetch_related("books"): | |
| books = [model_to_dict(book, ["name", "price"]) for book in author.books.all()] | |
| author = model_to_dict(author, ["name", "age"]) | |
| author["books"] = books | |
| authors.append(author) | |
| # json.dumps(authors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment