I'm trying to figure out how to filter QuerySet using date extracted from datetime.
I use Django-filter
and I can't compose such lookup without iterating over QuerySet which is very uneffective.
I tried datetime__date__gte
which doesn't work.
class MyReservationsFilter(FilterSet):
datetime__lte = DateFilter(method='datetime_filter',name='lte')
class Meta:
model = Reservation
fields = {'status': ['exact'],
# 'datetime': ['lte', 'gte'],
'destination_from': ['exact'],
'destination_to': ['exact'],}
def datetime_filter(self, queryset, name, value):
lookup = 'datetime__'+name
return queryset.filter(**{lookup:value})
Do you know what to do?
I can't use datetime__lte/gte
because:
I have a Reservation
object r.
>> r.datetime
>> datetime.datetime(2017, 8, 31, 17, 55)
>> r.datetime.date()
>> datetime.date(2017, 8, 31)
So now I try to filter based on date:
Reservation.objects.filter(datetime__lte=datetime.date(2017, 8, 31),datetime__gte=datetime.date(2017, 8, 31))
>> []
It's because it doesn't look only on date but on time too. So I need to extract date to be able to filter properly.