Home > database >  DRF SearchFilter Datetimefield Unsupported lookup 'gte'
DRF SearchFilter Datetimefield Unsupported lookup 'gte'

Time:10-09

I have a field timestamp which is a DateTime field when I'm filtering by this field in the shell it works fine with '__gte' or '__lte'

$ python manage.py shell     
>>> from inventory.models import Order
>>> Order.objects.filter(timestamp__date__gte=('2022-06-06'))
>>> <QuerySet [<Order: ID: 22>, <Order_id: 27>, ....]

but when I use SearchFilter it raises an error django.core.exceptions.FieldError: Unsupported lookup 'gte' for DateField or join on the field not permitted, perhaps you meant gte or gt or lte?

models.py

class Order(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)

views.py

from rest_framework.generics import ListAPIView
from rest_framework import filters

class Invoices(ListAPIView):
    serializer_class = InvoicesSerializer
    permission_classes = [IsAuthenticated, CustomModelPermissions]
    queryset = serializer_class.Meta.model.objects.all()
    filter_backends = [filters.SearchFilter]
    search_fields = ['timestamp__date__gte']

CodePudding user response:

Your filter doesn't work because, as per docs,

The search_fields attribute should be a list of names of text type fields on the model, such as CharField or TextField

If you want GTE lookup then you will need to add a FilterSet, e.g. like in How to create datetime filter using Django Rest Framework Filters.

CodePudding user response:

Just try to apply filter without __date

Order.objects.filter(timestamp__gte= datetime.date(2022,6,6))

Or

Order.objects.filter(timestamp__gte='2022-06-06')

Because your field timestamp is already date field

  • Related