I want to get the latest date from my database. Here is my sql statement.
select "RegDate" from "Dev" where "RegDate" = ( select max("RegDate") from "Dev")
It works in my database. But how can I use it in django?
I tried these codes but it return error. These code are in views.py.
Version 1:
lastest_date = Dev.objects.filter(reg_date=max(reg_date))
Error:
'NoneType' object is not iterable
Version 2:
last_activation_date = Dev.objects.filter(regdate='reg_date').order_by('-regdate')[0]
Error:
"'reg_date' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
I’ve defined reg_date at beginning of the class.
What should I do for this?
Advertisement
Answer
You make things too complicated, you simply order by regdate
, that’s all:
last_activation_dev = Dev.objects.order_by('-regdate').first()
The .first()
will return such Dev
object if it is available, or None
if there are no Dev
objects.
If you only are interested in the regdate
column itself, you can use .values_list(..)
:
last_activation_date = Dev.objects.order_by('-regdate').values_list('regdate', flat=True).first()
By using .filter()
you actually were filtering the Dev
table by Dev
records such that the regdate
column had as value 'reg_date'
, since 'reg_date'
is not a valid datetime format, this thus produced an error.