使用django聚合作为过滤子句

时间:2011-03-10 01:07:33

标签: django django-models python

有更好的方法吗?

# Get an instance of the class I am interested in. It has a manytomany relation
instance = Class.objects.get(pk=1)

# Get the highest start date out of all the objects in the manytomany set
max_date = instance.related_set.aggregate(Max("start_date"))

# Return the object with the highest start date in the manytomany set
query_result = instance.related_set.filter(start_date=max_date['start_date__max'])

必须有更优雅的方法才能做到这一点吗?

1 个答案:

答案 0 :(得分:1)

使用latest()方法获取“最大”日期是否符合您的需求?

django-query-using-order-by-and-latest

可能会引起人们的兴趣。