gpt4 book ai didi

python - APIView 上的 django 过滤器

转载 作者:太空狗 更新时间:2023-10-30 01:45:41 43 4
gpt4 key购买 nike

我有一个 APIView 类,用于显示所有租金以及发布和删除等。现在我想要搜索功能,所以我尝试使用 DjangoFilterBackend,但它不起作用。我在文档中看到,它已与 ListAPIView 一起使用,但我如何在 APIView 中使用它。

class Rent(APIView):
"""
List all the rents if token is not provided else a token specific rent
"""
serializer_class = RentSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('city', 'place', 'property_category',)
search_fields = ('=city', '=place')
def get(self, request, token=None, format=None):
reply={}
try:
rents = Rental.objects.all()
if token:
rent = Rental.objects.get(token=token)
reply['data'] = self.serializer_class(rent).data
else:
reply['data'] = self.serializer_class(rents, many=True).data
except Rental.DoesNotExist:
return error.RequestedResourceNotFound().as_response()
except:
return error.UnknownError().as_response()
else:
return Response(reply, status.HTTP_200_OK)

当我在 url 中使用以下参数搜索租金时,我得到了所有租金,而我应该只得到位于加德满都市和 koteshwor 地点的租金

http://localhost:8000/api/v1/rents?city=Kathmandu&place=Koteshwor

最佳答案

要使用 DjangoFilterBackend 的功能,您可以合并 GenericViewSet 中的 filter_queryset 方法,它是继承自 APIView 的 DRF 类,并且导致 DRF 中所有特定的“通用” View 类。它看起来像这样:

def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset

https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py

关于python - APIView 上的 django 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906253/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com