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

303 views
Skip to first unread message

Sencer Hamarat

unread,
Aug 5, 2022, 7:03:50 AM8/5/22
to django...@googlegroups.com
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

Satyajit Barik

unread,
Aug 5, 2022, 3:24:43 PM8/5/22
to django...@googlegroups.com
You can use here Django prefetch_related query.


Regards,
Satyajit

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZhhNW0bAZjpetbvwQdRx03fiVTtL2gYGTtuvzFKRKJfvQ%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages