[Django]-Django get child object through parent

5👍

You can get to a child object from parent like you did in the final for loop, but you’d also need to check if the child exists for parent like so:

for obj in A.objects.all():
    try:
        if obj.b.field1 == 'something':
            do some operation
    except ObjectDoesNotExist:
        # obj does not have a child of class B

    try:
        if obj.c.field2 == 5:
            do some other operation
    except ObjectDoesNotExist:
        # obj does not have a child of class C

You can also combine this into a single query using Q objects:

A.objects.filter(Q(b__isnull=False, b__field1='something') | Q(c__isnull=False, c__field2=5))

This would return objects of class A

0👍

Perhaps this may be useful for someone. hasattr will return True for the correct child instance, False otherwise. Please note class name is in smallcase for hasattr parameter.

for obj in A.objects.all():
    if obj.hasattr('b'):
       # do something specific to b
    if obj.hasattr('c'):
       # do something specific to c

Leave a comment