加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 关于APIView的django过滤器

发布时间:2020-12-20 12:12:40 所属栏目:Python 来源:网络整理
导读:我有一个APIView类显示所有的租金和发布和删除等.现在我想要搜索功能,所以我试图使用DjangoFilterBackend,但它无法正常工作.我在文档中看到它已经与ListAPIView一起使用但是我如何在APIView中使用它. class Rent(APIView): """ List all the rents if token
我有一个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)

当我在网址中使用以下参数搜索租金时,我得到所有的租金,而我应该只获得位于加德满都市的租金并放置koteshwor

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

解决方法

这里如果您正在使用API??View,那么与过滤器无关.所以你必须这样做

get_data = request.query_params #or request.GET check both

然后

Rental.objects.filter(city=get_data['city'],place=get_data['place'])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读