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.
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?
Thanks in advance!
I use this in my own projects. The order_by and values make it group by name
from django.db import models
Model.objects.order_by('name').values('name').annotate(max_timestamp=models.Max("timestamp"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.