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

10 Feb · by Tim Kamanin · 1 min read

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/base.py file (here: https://github.com/django/django/blob/1.10.5/django/core/serializers/base.py#L84) and you should see

for field in concrete_model._meta.local_fields:

change it to

for field in concrete_model._meta.fields:

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: https://github.com/django/django/tree/1.10.5/django/core/serializers.

Alright then, happy coding!

Comments

Required for comment verification