I want to filter a model that I've created by month & year.
This is my model:
class Cotisation(models.Model):
date = models.DateTimeField()
campagne = models.ForeignKey(Campagne, on_delete=models.CASCADE)
class Meta:
managed = True
db_table = 'cotisations'
ordering = ['-id']
This is my view:
class CotisationViewSet(viewsets.ModelViewSet):
queryset = Cotisation.objects.all()
serializer_class = CotisationSerializer
pagination_class = StandardResultsSetPagination
filter_backends = (filters.SearchFilter, DjangoFilterBackend, filters.OrderingFilter,)
filter_class = CotisationFilter
search_fields = ('organism__name', 'organism__num_onic')
ordering_fields = ('date',)
And this is my filter class:
class CotisationFilter(django_filters.FilterSet):
month = django_filters.NumberFilter(field_name='date', lookup_expr='month')
year = django_filters.NumberFilter(field_name='date', lookup_expr='year')
class Meta:
model = Cotisation
fields = ['organism__id', 'campaign__id', 'campaign__year', 'month', 'year']
When I try to query by year it works well:
GET http://{{URL}}/cotisations/?year=2019
But it doesn't work when I try with month:
GET http://{{URL}}/cotisations/?month=10
Thank you in advance.
Best, Jeremy.
PS: And Happy new year!
SOLUTION:
@Horion answered perfectly.
Here is the answer that solved the issue: Answer