[Django]-Django: get related objects of related objects and pass to template

4👍

Say you have an instance of A called a.

bs = a.b_set.all()
for b in bs:
    cs = b.c_set.all()

The iteration over the elements might be done in the template itself.

In order to avoid multiple queries you can prefetch related objects.

1👍

So this would be the code for your view. I am not sure from which object(s) are given in the args/kwargs.

from django.views.generic import TemplateView

class YourView(TemplateView):
    template_name = 'yourtemplate.html'

    def get_context_data(self, **kwargs):
        a = kwargs.get('a')
        b = kwargs.get('b')
        ctx = super().get_context_data(**kwargs)

        ctx['all b related to a'] = a.b_set.all()
        ctx['all c related to b'] = b.c_set.all()
        return ctx

If you have to combine querysets, say multiple querysets of cs for each b as @s_puria suggested, you can use the UNION operator https://docs.djangoproject.com/en/1.11/ref/models/querysets/#union

Leave a comment