Limiting Child Records from QuerySet

Given models like these:

Family

Parent

  • foreignkey(Family)
  • birth_year(int)

Child

  • foreignkey(Parent)
  • birth_year(int)

How can I use the ORM to get a queryset or object that contains a Family, its youngest Parent, and only that Parents’ Children?

Closest I got was:
family= get_object_or_404(Family, pk=self.kwargs[‘pk’])
latest = family.parent_set.all().order_by(‘-birth_year’)[0] // id = 4
print(Family.objects.filter(parent_set__id=latest.id))

But all parent records are still included even though I am filtering by a parent’s Id I found in a separate query.

I’d like it to work like the following SQL, but also pull in all the Children of the youngest Parent automatically like it currently does. It just gets all Parents of the Family

SELECT family.id, family.birth_year FROM family INNER JOIN parent ON (family.id = parent.family_id) WHERE parent.id = 4

Thanks for reading!

The following should assuming you defined proper related_name between your relationships

parents = (
    Parent.objects.filter(family=self.kwargs["pk"])
    .select_related("family")
    .prefetch_related("children")
)

try:
    latest_parent = parents.latest("birth_year")
except Parent.DoesNotExist:
    raise Http404

family = latest_parent.family
latest_parent_children = latest_parent.children.all()

That works well, thanks! I think I understand the select_ and prefetch_related better now.

What I am ultimately trying to accomplish is to use an inline form inside an inline form as shown in this code:
https://github.com/philgyford/django-nested-inline-formsets-example/tree/main

It works to emulate the django admin forms but always includes all Parents and their Children rather than a specific one.

Filtering to a specific Parent seems to require overriding get_object on the FormView-based class I create to generate the view.

But I cannot figure out how to return a Family object from get_object that only has the specific Parent and its Children on it.