我已实现以下视图,以根据提供的特定查询来过滤交易。有没有一种方法可以根据提供的查询来动态过滤,例如,人们可能只想查询year
和month
,甚至只想查询一个查询。其余查询值最终将具有None
值,不应包含在过滤器中。
class ReportTransactionsFilterAPIView(APIView):
def get(self, request, format=None):
year = self.request.GET.get('year')
month = self.request.GET.get('month')
subcounty = self.request.GET.get('subcounty')
ward = self.request.GET.get('ward')
fromDate = self.request.GET.get('fromDate')
toDate = self.request.GET.get('toDate')
qs = LiquorReceiptTrack.objects.all()
qs = LiquorReceiptTrack.objects.filter(
Q(date_recieved__range=[fromDate,toDate])|
Q(date_recieved__year=year)|
Q(date_recieved__month=month)|
Q(sub_county__iexact=subcounty)|
Q(ward__iexact=ward)
)
答案 0 :(得分:1)
您可以使用django-filter作为解决方案。此外,有关更多信息,您可以访问https://www.django-rest-framework.org/api-guide/filtering/
答案 1 :(得分:0)
仅使用if
,为什么在这里使用Q
?:
year = self.request.GET.get('year')
month = self.request.GET.get('month')
subcounty = self.request.GET.get('subcounty')
ward = self.request.GET.get('ward')
fromDate = self.request.GET.get('fromDate')
toDate = self.request.GET.get('toDate')
qs = LiquorReceiptTrack.objects.all()
if year:
qs = qs.filter(date_recieved__year=year)
if month:
qs = qs.filter(date_recieved__month=month)
...
答案 2 :(得分:0)
浏览了django-filter文档并重构了列表视图:
class TransactionFilter(django_filters.FilterSet):
date_range = DateFromToRangeFilter()
month = django_filters.NumberFilter(field_name='date_recieved', lookup_expr='month')
year = django_filters.NumberFilter(field_name='date_recieved', lookup_expr='year')
date = django_filters.DateFilter(field_name='date_recieved', lookup_expr='exact')
sub_county = django_filters.CharFilter(lookup_expr='icontains')
ward = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = LiquorReceiptTrack
fields = ['date','month','year','date_range','sub_county','ward']
class ReportTransactionsFilterAPIView(generics.ListAPIView):
queryset = LiquorReceiptTrack.objects.all()
serializer_class = ReceiptDetailSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = TransactionFilter