Django filter by datetime month__gte is not working

3.6k views Asked by At

I'm using Django 2.2

I have a created field of DateTime type.

I'm using following command to filter the records which are greater than specific date

q.filter(created__year__gte=2020, created__month__gte=3, created__day__gte=1)

In my database there are records for March (3) month and more but not for February (2).

When above command is executed, it gives me queryset list of data greater than March 1. But when I use the following command

q.filter(created__year__gte=2020, created__month__gte=2, created__day__gte=28)

Where month is February (2), it is not giving any data and the queryset is blank.

Using datetime object gives error

received a naive datetime (2020-03-01 00:00:00) while time zone support is active

Why filter is not working with gte even when month is less than 3?

3

There are 3 answers

0
Anuj TBE On BEST ANSWER

The error was not with the Django setup, instead it was with the MySQL configuration due to missing timezone data.

Check this answer for how to resolve this error

https://stackoverflow.com/a/60844090/3719167

2
Andrey Nelubin On

Why do you want to filter like this? In your case it is totally unnecessary. Just filter by date strictrly

q.filter(created__gte=datetime.datetime(2020, 3, 1))
1
marxin On

Use:

q.filter(created__date__gte=datetime.date(2020, 3, 1))

Regarding the filter, its working perfectly when month < 3, but if you specify that day > 28, then its already narrowing results set to only data that was crated between 29-31 day for every month, not only Feb. And most likely its not what you want.