Here is my custom filter class
class CarFilter(FilterSet):
pickup_date = NumberFilter(method='filter_pickup_date_timestamp')
dropoff_date = NumberFilter(method='filter_dropoff_date_timestamp')
class Meta:
model = Car
fields = ['area_coverage', 'is_published', 'owner']
def filter_pickup_date_timestamp(self, queryset, name, value):
pickup_date = datetime.fromtimestamp(float(value))
for car in queryset:
if len(Reservation.objects.filter(
dropoff_date__gte=pickup_date,
is_active=True,
item_type='car',
item=car.item,
)) > 0:
return None
return queryset.filter()
def filter_dropoff_date_timestamp(self, queryset, name, value):
dropoff_date = datetime.fromtimestamp(float(value))
for car in queryset:
if len(Reservation.objects.filter(
pickup_date__lte=dropoff_date,
is_active=True,
item_type='car',
item=car.item,
)) > 0:
return None
return queryset.filter()
Is it possible to create such method, that will filter by both arguments pickup_date
and dropoff_date
? How to get value
from another filter filed in method? Because know I have to filter through Reservation
model twice.
It is possible, because in method request can be accessed through self
def filter_pickup_date_timestamp(self, queryset, name, value):
pickup_date = value
dropoff_date = self.request.query_params.get('dropoff_date')