[Answered ]-Query child objects through parent model – Django

1👍

You can work with .select_related(…) [Django-doc] to fetch the data of the teacher and/or doctor in the same query, so:

queryset = employee.objects.select_related('doctor', 'teacher')

and then try to access the attribute if that is a subclass:

for item in queryset:
    try:
        doctor_details = item.doctor
    except AttributeError:
        pass  # not a doctor

This is essentially what the django-polymorphic package [PyPI]
does internally.

Leave a comment