'get first object from every type in Django query

I have a query like this:

objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at')

is there a way to fetch only the first item of every type and not all the items with these types by adding a condition to this query?



Solution 1:[1]

Yes, there is a manual way.

type_list = [1,2,3,4]
new_list = []

for each_type in type_list:
    latest_obj = MyModel.objects.filter(type=each_type).order_by('-created_at').first()
    new_list.append(latest_obj)

This new_list contains the latest object or each type.

Or

objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('type', '-created_at').distinct('type')

Reference: Django distinct

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1