下表载于Django-1.11:
class Market(models.Model):
slug = models.SlugField(...)
active = models.DateTimeField(...)如果slug是避免重复值的外键,那就太好了,但事实并非如此,我正在处理第三方应用程序。
data = [
{'id': 1, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>)'},
{'id': 2, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>)'},
{'id': 3, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>)'},
{'id': 4, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>)'},
]我正在寻找一个查询,这将返回最新的条目与鼻涕虫test-1和最近的条目与鼻涕虫test-2。
annotate我只是收到结果和他们的日期时间:
Market.objects.values('slug').annotate(Max('active'))
Out[11]: <QuerySet [
{'active__max': datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'},
{'active__max': datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'}
]>这个结果似乎没有遵循医生们。我做错了什么?是SlugField不允许“分组”吗?
发布于 2017-10-23 21:42:18
看起来,您需要通过结果查询中的order_by()添加空默认订购-或按顺序订购,可以将额外的字段添加到group by。
试一试:
Market.objects.values('slug').annotate(Max('active')).order_by()https://stackoverflow.com/questions/46898464
复制相似问题