简体   繁体   中英

Filter date by month DRF

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

I have used the exact filter (on PG) several times and there were no problems.

Probably you are using MySQL as the default database, if so, then you have to install time zone definition to your database to be able to use this filter when USE_TZ = True.

Check this ticket and this question

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM