Is it possible to use `__date` for a `timestamp` field in `filterset_fields` list of `DjangoFilterBackend`

Viewed 38

I am using ListAPIView to list the records from my database table which is represented as ExpiredOrders(models.Model) in models.py.

The Django model has several columns along with created_at and modified_at as timestamp.

I want to filter the records on the created_at against the query parameters created_at.

I am trying to use the DjangoFilterBackend to achieve the same.

filter_backends = [DjangoFilterBackend]
filterset_fields = ['craeted_at__date']

However, it return me an error -

'Meta.fields' must not contain non-model field names: created_at__date

As created_date is a timestamp and in query parameter I will only get the date as YYYY-MM-DD, I am using __date to make the record of database table comparable with the query parameter.

The other way to achieve this is -

def get_queryset(self):

        try:

            queryset = ExpiredOrders.objects.filter(created_at__date=self.query_params['created_at'])

        except:

            queryset = ExpiredOrders.objects.all()
        
        return queryset

I want to know if it is possible to get it done by just defining the filed name in the list filterset_fields.

Also, please explain me what does this __ means here.

Best to my knowledge it is a convention to represent class variable or methods which must not be used with the objects of other class or subclasses. Perhaps, this concept is known as name mangling in Python.

In the Django documentation I have seen many of these --. Some of those are -

gte - greater than or equal to

lte - less than or equal to

et - equal to

1 Answers

Use a FilterSet class to create a filter with custom filters.

class ExpiredOrderFilter(filters.FilterSet):
    created_at__date = filters.DateFilter(field_name='created_at__date')

    class Meta:
        model = ExpiredOrder
        fields = ['created_at',]

Now instead of filterset_fields user filterset_class

filter_backends = [DjangoFilterBackend]
filterset_class = ExpiredOrderFilter
Related