How To Export Django Model Data Along With Its Parent Model Data via dumpdata Command

Feb 10, 2017 · Updated: Jul 12, 2021 · by Tim Kamanin

Django dumpdata command lets us export model objects as fixtures and to store them in json / xml formats.

All is good and works fine until you need to export a model that is a child of a concrete model and shares two database tables (one for parent another is for the model).

If you ever happen to export such a model, you'll notice that dumpdata command exports only child model data. Which is desired behavior in most cases.

But what if you need to get parent + child model data as a single json object?

Well, you may need to temporarily hack the core (naughty naughty!).

Here's how to do that: as of Django 1.10.5 you need to find a line number 84 in django/core/serializers/ file (here and you should see:

for field in concrete_model._meta.local_fields:
    # code goes here

change it to

for field in concrete_model._meta.fields:
    # code goes here

and voila, you model is now exported with a parent model data as a single JSON object.

Just don't forget to revert your code changes afterward, because hacking core is bad and you likely need to do this change for one-time operation.

However, If you need to use this approach on a constant basis, consider creating a custom serializer and applying your changes in it. You can find serializer examples here:

Alright then, happy coding!

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓