首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过仅使用Djangorestframework中的DateTime字段传递DateFilter参数来过滤Json响应

如何通过仅使用Djangorestframework中的DateTime字段传递DateFilter参数来过滤Json响应
EN

Stack Overflow用户
提问于 2020-06-22 12:24:48
回答 1查看 94关注 0票数 0

我需要一个json响应,只需输入一年的参数,而不是日期,注意:我在db中有大约25列数据,所以要寻找简单的解决方案,谢谢。

代码语言:javascript
运行
复制
models.py:
    '''class indicator(models.Model):
        fiscalyearend = models.DateField(db_column='FiscalYearEnd') 
    
    serializers.py:
    
    class IndicatorSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = indicator
            fields = ['fiscalyearend']
    
    views.py
    filters:
    
       class indicatorDataBaseListView1Filter(filters.FilterSet):
        fiscalyearend = filters.DateFilter('fiscalyearend',label=('With start date'),lookup_expr='contains')
    
    
    view
    
       class indicatorView1(generics.ListAPIView):
        serializer_class = KeyperformanceindicatorSerializer
        queryset = Indicator.objects.all() #vice versa for get_queryset method
        filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter)
        filterset_class = indicatorDataBaseListView1Filter'''
    
    
    url : localhost:8000/indicator/?fiscalyearend=2019
    
    json output : enter a valid date 
    
    my current date formate is 2019-01-01
    
    
     i need to filter the json just by entering the year in the url instead of entire date
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-22 16:07:11

如果您只使用参数yearmonth查找,您可以使用django_filters.NumberFilter,然后它将神奇地在您的localhost:8000/indicator/?fiscalyearend=2019上工作,同样用于过滤month

代码语言:javascript
运行
复制
class indicatorDataBaseListView1Filter(django_filters.FilterSet):
    # field name <fiscalyearend> will eventually used as query parameter?<field_name>
    fiscalyearend = django_filters.NumberFilter(field_name= 'fiscalyearend', lookup_expr='year')

视图

代码语言:javascript
运行
复制
class indicatorView1(generics.ListAPIView):
    serializer_class = KeyperformanceindicatorSerializer
    queryset = Indicator.objects.all() #vice versa for get_queryset method
    filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter)
    # note: filter_class 
    filter_class = indicatorDataBaseListView1Filter
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62514418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档