I need to find the latest date entry among multiple DateTimeFields.
models.py:
class Presentation(models.Model):
start = models.DateTimeField(blank=True, null=True, verbose_name=_(u'Start'))
end = models.DateTimeField(blank=True, null=True, verbose_name=_(u'End'))
I am aware of latest() which sadly only supports querying a single field.
EDIT: I am looking for a one-query solution, if it exists.
For a one query solution you can use django's extra() queryset method:
latest_obj = Presentaion.objects.extra({"latest_date":"greatest(start, end)"}).order_by('latest_date')[0]
This will give you the object with the latest timestamp. latest_obj
has now an extra attribute latest_date
latest_obj.latest_date
Using extra()
is not recommended and will be deprecated in future versions.
Use this method as a last resort. This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods.
In django1.9 a database function Greatest
was introduced. Now you can use annotate
for that:
from django.db.models.functions import Greatest
latest_obj = Presentaion.objects.annotate(last_date=Greatest('start', 'end')).order_by('last_date')[0]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments