简体   繁体   English

如何使用Django ORM进行查询,以便基于特定组中的datetime字段返回最新条目?

[英]How to use Django ORM to make a query so that it returns the latest entry based on a datetime field in a particular group?

I have a model with datetime field which is the time stamp of when the row was added and in this model/table continuous entries are being made at certain intervals from various sources which are referenced through a name which is also a field in the model. 我有一个带有datetime字段的模型,该字段是添加行的时间戳,在此模型/表中,是从各种来源中按一定的间隔连续输入的,这些来源通过名称(也是该模型中的字段)引用。

I need to form a query so that I will fetch the row with latest datetime when grouped by name. 我需要形成一个查询,以便在按名称分组时获取具有最新日期时间的行。

ie lets say for example table is something like this: 即假设例如表是这样的:

timestamp              entry_name
22 march 12:30         First
22 march 12:32         Second
22 march 12:42         First
22 march 12:50         Second

My query should result in: 我的查询应导致:

22 march 12:42         First
22 march 12:50         Second

As they are the latest entries with respect to "First" and "Second" group. 因为它们是有关“第一”和“第二”组的最新条目。

Now using raw query its pretty straight forward: 现在使用原始查询非常简单:

select *,max(datetime) from entry_table GROUP BY entry_name;

Is there any simple way to do this through the ORM? 是否有通过ORM做到这一点的简单方法?

Thanks in advance! 提前致谢!

I use this in my own projects. 我在自己的项目中使用它。 The order_by and values make it group by name order_by和值使它按名称分组

from django.db import models
Model.objects.order_by('name').values('name').annotate(max_timestamp=models.Max("timestamp"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM