Friday, August 5, 2022

How to get last child object of a parent model by query

Hi,

Let's say there are two related models 

class Parent(models.Model):
    ...

class Child(models.Model):
    parent = models.ForeingKey(Parent)

I need to fetch every last child of specific parent objects by query.
Is there a way to do this instead iterating Parent objects to gather last childs like:

last_childs = list()
for parent in Parent.objects.filter(id__in=[1, 2, 3, 4]):
    last_childs.append(parent.child_set.last())


Kind regards,
Sencer HAMARAT

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZhhNW0bAZjpetbvwQdRx03fiVTtL2gYGTtuvzFKRKJfvQ%40mail.gmail.com.

No comments:

Post a Comment