从 Django 查询中的每种类型获取第一个对象
get first object from every type in Django query
我有这样的查询:
objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at')
有没有办法通过向此查询添加条件来仅获取每种类型的第一项而不是所有具有这些类型的项目?
是的,有一个手动方式。
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)
此 new_list 包含最新对象或每种类型。
或者
objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('type', '-created_at').distinct('type')
我有这样的查询:
objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at')
有没有办法通过向此查询添加条件来仅获取每种类型的第一项而不是所有具有这些类型的项目?
是的,有一个手动方式。
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)
此 new_list 包含最新对象或每种类型。
或者
objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('type', '-created_at').distinct('type')