我有一个模特:
class ModelTest(models.Model):
test_name = models.CharField(max_length=100)
test_field = models.IntegerField()
test_date = models.DateTimeField()
test_make = models.IntegerField()
现在,我想要相同test_field 的行 max test_date 。
我所做的是ModelTest.objects.values('test_field').annotate(td=Max('test_date')).values('test_field','test_date')
。
现在,我想要获得所有其他字段值以及所选行。如果我尝试在任何values
中添加它们,则注释不起作用。
可能的解决方案是什么?
更新:
测试数据:
test_name | test_field | test_date | test_make
test1 | 1 | 2012-01-23 15:24:10.389+05:30 | 3
test2 | 2 | 2012-01-23 15:24:26.747+05:30 | 5
test3 | 3 | 2012-01-23 15:27:19.033+05:30 | 1
test4 | 2 | 2012-01-23 15:29:45.098+05:30 | 4
test5 | 3 | 2012-01-23 15:54:01.322+05:30 | 2
现在,我希望输出为:
test1 | 1 | 2012-01-23 15:24:10.389+05:30 | 3
test4 | 2 | 2012-01-23 15:29:45.098+05:30 | 4
test5 | 3 | 2012-01-23 15:54:01.322+05:30 | 2
答案 0 :(得分:2)
您可以使用以下内容:
[ModelTest.objects.get(test_field=x['test_field'],test_date=x['td'])
for x in ModelTest.objects.values('test_field').annotate(td=Max('test_date'))
]
由于您的注释仅返回您想要的字段,因此只有test_field
+ test_date
的一个组合符合您的结果。
Annotate不返回任何对象,只返回作为dicts的匹配列表,因此您必须再次查询对象。
更好的方法是编写自己的自定义查询,并将其与extra
答案 1 :(得分:0)
如果我理解你,我不是100%,但是如果你在这里提到Django指南:https://docs.djangoproject.com/en/dev/topics/db/aggregation/#cheat-sheet
要返回具有整行的聚合查询集,其中某些条件符合聚合子句,您只需编写:ModelTest.objects.all()。annotate(td = Max('test_date'))。严格来说,如果max('test_date')在表格中多次出现,这将为您提供多行。
如果您首先需要过滤查询集,则可以这样做,而不是使用all(),您可以使用filter(criteria_here)并将其链接,就像使用任何其他查询集一样。