Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Knowledge base documentation
Knowledge base documentation

Django

  • 1. Existence of key inside a nested json field in Django with PostgreSQL
  • 2. How to use explain from sql in a Django queryset
  • 3. List all related model in Django
  • 4. Safely move a model between apps

Linux

  • 1. Usefull command for CEPH
Back to top

3. List all related model in Django¶

Using NestedObjects from Django’s admin utils, you can collect all related objects of a model instance. Could be usefull to check for related objects before deleting a model instance or for exporting related data.

from django.contrib.admin.utils import NestedObjects

collector = NestedObjects(using="default")
collector.collect([MyModel.objects.get(pk=123456)])

collector.data is a dictionary where the keys are the model classes and the values are lists of objects of that class. You can iterate over it to access all related objects.

for model, related_objects in collector.data.items():
    print(f"Model: {model.__name__}, Related Objects count: {len(related_objects)}")

3.1. Get a flat list of all related objects¶

Utilizing itertools.chain, you can flatten the list of related objects into a single list:

from itertools import chain

objects = list(chain.from_iterable(collector.data.values()))

3.2. Exporting related models in JSON format¶

We could also serialize the objects to JSON format for export for later analysis or backup (don’t use this in production as it can be slow for large datasets):

from django.core import serializers

with open("export.json", "w") as f:
    f.write(serializers.serialize("json", objects))

Source:

  • Django NestedObjects

Tags: Django, Python, JSON, Export, Related model, itertools, NestedObjects, Serialization, from_iterable

Next
4. Safely move a model between apps
Previous
2. How to use explain from sql in a Django queryset
Copyright © 2025, Legrems
Made with Sphinx and @pradyunsg's Furo
On this page
  • 3. List all related model in Django
    • 3.1. Get a flat list of all related objects
    • 3.2. Exporting related models in JSON format