[英]how can i filter the Json response by only passing the Year parameter to the DateTime field using DateFilter in Djangorestframework
i need a json response just by entering the year in parameter instead of date Note: i have around 25 columns of data in db so looking for simple solution Thanks我需要一个 json 响应,只需在参数中输入年份而不是日期注意:我在 db 中有大约 25 列数据,所以寻找简单的解决方案谢谢
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
If you look up only using parameter year
or month
, you can use django_filters.NumberFilter
, then it will magically work on your localhost:8000/indicator/?fiscalyearend=2019
, same for filtering the month
如果您只使用参数
year
或month
查找,您可以使用django_filters.NumberFilter
,那么它将神奇地在您的localhost:8000/indicator/?fiscalyearend=2019
上工作,同样用于过滤month
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')
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.