有没有办法在我创建的 GET
函数中使用Django REST过滤器?
当我使用它时它起作用:
class ContactListView(generics.ListAPIView):
queryset = Profile.objects.all()
serializer_class = UserContactListSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'last_name',)
但是我想让它在我创建的 GET 函数中工作:
def get(self, request, pk, format=None):
contacts = Profile.objects.get(pk=pk)
serializer = UserContactListSerializer(contacts)
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'last_name',)
return Response(serializer.data)
答案 0 :(得分:1)
在Get函数中......
假设您有一个类似mywebsite.com/mypage/?search=[searchterm]
然后在你的GET函数中使用:
def get(self, request):
filterurl = self.request.query_params.get('search', None)
contacts = Profile.objects.all()
if filterurl is not None:
contacts = Profile.objects.filter([fieldname]=filterurl)
return Response(contacts)
答案 1 :(得分:-1)
在get函数中,View是一个实例。所以filter_backends是这个实例的属性。您必须重新更新其属性并调用“filter_queryset”函数。 “filter_backends”将在此函数中使用:
def get(self, request, pk, format=None):
self.filter_backends = (filters.SearchFilter,)
self.search_fields = ('name', 'last_name',)
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)