Skip to content

Instantly share code, notes, and snippets.

@z4none
Created June 26, 2015 00:59
Show Gist options
  • Select an option

  • Save z4none/0e9a26ca6ebb39627b59 to your computer and use it in GitHub Desktop.

Select an option

Save z4none/0e9a26ca6ebb39627b59 to your computer and use it in GitHub Desktop.
django model to dict (with related model)
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