Как использовать фильтр DateTimeFilter в django-фильтре, передавая ему пользовательский параметр «метод»?

#python #django #django-filter

Вопрос:

Я пытаюсь вызвать конечную точку, настроенную как таковую:

https://www.nottherealurl.com/foods?транзакция_datetime=2020-01-01,2020-01-30

Я пытаюсь отфильтровать продукты, которые были проданы в течение определенного времени между датой начала и датой окончания. В данном случае между 2020-01-01 и 2020-01-30 годами.

У меня есть модель под названием Еда, и в ней есть поле под названием transaction_datetime .

 class Food(CustomMixin):
    ... other fields ...
    
     food_type = models.CharField(
        max_length=25,
        null=True,
        blank=True,
        choices=FOOD_TYPE_CHOICES,
    )

    transaction_datetime = models.DateTimeField(
        null=False,
        editable=False,
    )
    
    ... other fields ...

 

У меня есть настройка представления как таковая:

 class FoodView(ListAPIView):
    serializer_class = FoodSerializer
    filter_backends = (
        filters.OrderingFilter,
        filters.SearchFilter,
        filters.DjangoFilterBackend
    )
    filter_class = FoodFilter
    ordering_fields = (
        'name',
        'amount',
        'transaction_datetime',
        '=food_uuid',
    )
    ordering = ('-transaction_datetime',)
    search_fields = ordering_fields

    def get_queryset(self):
        return (
            Food.objects.prefetch_related('ingredients').filter(deleted_at__isnull=True)
 

Он FoodFilter настроен как таковой.

 class FoodFilter(django_filters.FilterSet):

    food_type = django_filters.CharFilter(method='filter_by_food_type')
    transaction_datetime = django_filters.DateTimeFilter(method='filter_by_transaction_datetime')


    def filter_by_food_type(self, queryset, name, value):
        print("RAN") # printed when I call the appropriate endpoint as stated below
        value_list = [x.strip() for x in value.split(',')]
        return queryset.filter(
            food_type__in=value_list
        )

    def filter_by_transaction_datetime(self, queryset, name, value):
        print("HELLLOOOO") # this does not show up at all when attempt to call endpoint to filter by transaction_datetime
        value_list = [x.strip() for x in value.split(',')]
        start_date = value_list[0]
        end_date = value_list[1]
        return queryset.filter(transaction_datetime__range=[start_date, end_date])

    class Meta:
        model = Food
        fields = {
            'cooking_state': ['exact'],
        }

 

I am able to use the following endpoint, and am certain that the queryset was filtered with the filter_by_food_type method.

endpoint url that works with filter_by_food_type :
https://www.nottherealurl.com/foods?food_type=vegan,vegetarian

But I am unable to run this url to filter my queryset by transaction_datetime :
https://www.nottherealurl.com/foods?transaction_datetime=2020-01-01,2020-01-30

I was wondering if this is because the DateTimeFilter does not accept method as a kwarg? But I am pretty sure it does since DateTimeFilter extends Filter doesn’t it? Could anyone tell me what I’m doing wrong and suggest a solution/fix ? Thank you 🙂