Lleims
Lleims

Reputation: 1353

Filtering django model using date

I need to filter some data from models using the date. I see some posts that speaks about ranges but I just want to see for example the rows of my table from the 22/04/2020, in other words, just one day.

Reading the documentation, I understood that I have to do the following,

import datetime

prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp=datetime.date(2020, 4, 22))
prueba = loads(serializers.serialize('json', prueba))
for p in prueba:
    print(p)

But appears the following warning:

RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-04-22 00:00:00) while time zone support is active.

And the list appears empty. I think the problem is that is just filtering using 2020-04-22 00:00:00 and not all the day. How can I fix this?

Between two dates is working but just one day I don't know how to do it.

import datetime

start_date = datetime.date(2020, 4, 22)
end_date = datetime.date(2020, 4, 23)
prueba = DevData.objects.order_by('-data_timestamp').filter(data_timestamp__range= (start_date,end_date))

PD: I have info rows in this day.

Thank you very much.

Upvotes: 2

Views: 37

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

You can make use of the __date lookup [Django-doc] to filter on the date of the timestamp:

import datetime

prueba = DevData.objects.order_by(
    '-data_timestamp'
).filter(
    data_timestamp__date=datetime.date(2020, 4, 22)
)

Upvotes: 1

Related Questions