Reputation: 123
I'm trying to filter my queryset on Datefield based on year and month. After searching a lot I found this answer and tried to use it. but when I use filter I got and empty list.
model.py:
class Sample(models.Model):
name = models.CharField(max_length=50)
date = models.DateField(auto_now=False, auto_now_add=False)
serializer.py:
class SampleSerializer(serializers.ModelSerializer):
class Meta:
model = Sample
fields = '__all__'
filter.py:
import django_filters # only for showing I use django_fliter not drf defult filter
from .models import Sample
class SampleDateFilter(django_filters.FilterSet):
month = django_filters.NumberFilter("date", lookup_expr='month')
year = django_filters.NumberFilter('date',lookup_expr='year')
class Meta:
model=Sample
fields = ['month','year']
views.py:
class SampleListview(generics.ListAPIView):
serializer_class = SampleSerializer
queryset = Sample.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_class = SampleFilter
I have an object in my database with this config:
{
"id": 1,
"name": "test",
"date": "2020-05-03", #date format %YYYY-%MM-%DD
}
without filter I got my list but I got nothing when I use queryparam:
http://127.0.0.1:8000/sample/?year=2020
http://127.0.0.1:8000/sample/?month=05
or any combination of both filters. I'm using:
django-filter==2.4.0
djangorestframework==3.12.4
Django==3.0.8
How can I fix this? Thanks
Upvotes: 0
Views: 295
Reputation:
Your filter set is wrong.
Try this:
import django_filters
from .models import Sample
class SampleDateFilter(django_filters.FilterSet):
month = django_filters.NumberFilter(field_name='date__month', lookup_expr='exact')
year = django_filters.NumberFilter(field_name='date__year', lookup_expr='exact')
class Meta:
models=Sample
fields = ['month','year']
Also you can use gte
lte
etc as expression
Upvotes: 2