Anton Belsky
Anton Belsky

Reputation: 399

How to filter children by parent field

Example, models.py:

class Guy(models.Model):
    name = models.CharField(max_length=30)


class Mom(models.Model):
    name = models.CharField(max_length=150, choices=MOTHER_NAMES, default=MOTHER_NAMES[0][0])
    guy = models.OneToOneField(Guy, on_delete=models.SET_NULL)

How to get queryset of Guys whose Mom's name is 'Sophia'

Upvotes: 2

Views: 354

Answers (1)

kamilyrb
kamilyrb

Reputation: 2627

You can find the validation_contract_ids of mothers whose name is Sophia and you can find the children whose id in this validation_contract_ids.

You can use following query:

Guy.objects.filter(id__in=Mom.objects.filter(name='Sophia').values_list('guy_id',flat=True))

Upvotes: 2

Related Questions