简体   繁体   English

按月DRF筛选日期

[英]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: 但是当我尝试使用month时它不起作用:

GET http://{{URL}}/cotisations/?month=10

Thank you in advance. 先感谢您。

Best, Jeremy. 最好,杰里米。

PS: And Happy new year! PS:新年快乐!

SOLUTION: 解:

@Horion answered perfectly. @Horion完美回答。

Here is the answer that solved the issue: Answer 下面是解决这一问题的答案: 答案

I have used the exact filter (on PG) several times and there were no problems. 我已经多次使用精确的过滤器(在PG上),没有问题。

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. 可能是您将MySQL用作默认数据库,如果是这样,那么当USE_TZ = True时,必须将时区定义安装到数据库中才能使用此过滤器。

Check this ticket and this question 检查这张票这个问题

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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