如何使用Django ORM进行查询,以便根据特定组中的日期时间字段返回最新条目?

时间:2022-06-28 13:21:28

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.

我有一个带有日期时间字段的模型,该字段是添加行的时间戳,在此模型/表格中,连续条目是从各种来源以特定间隔进行的,这些来源通过名称引用,该名称也是模型中的字段。

I need to form a query so that I will fetch the row with latest datetime when grouped by name.

我需要形成一个查询,以便在按名称分组时获取最新日期时间的行。

i.e. 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!

提前致谢!

1 个解决方案

#1


1  

I use this in my own projects. The order_by and values make it group by name

我在自己的项目中使用它。 order_by和values使其按名称分组

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

#1


1  

I use this in my own projects. The order_by and values make it group by name

我在自己的项目中使用它。 order_by和values使其按名称分组

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