【发布时间】:2017-10-23 21:00:57
【问题描述】:
我在 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>)'},
]
我正在寻找一个查询,它将返回带有 slug test-1 的最新条目和带有 slug test-2 的最新条目。
Using 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'}
]>
此结果似乎与the docs 不一致。我究竟做错了什么?是SlugField不允许“分组”吗?
【问题讨论】:
标签: python django django-queryset