gpt4 book ai didi

python - Django Rest Framework ViewSet 在覆盖 list() 方法时丢失分页、SearchFilter 和 OrderingFilter

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:12 26 4
gpt4 key购买 nike

我必须重写 DRF ViewSet 的默认 list() 方法,但是当我这样做时,所有过滤、排序和分页都停止工作。

这是 ViewSet 的代码:

class ZoneViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
queryset = models.Zone.objects.all()
serializer_class = serializers.ZoneSerializer
filter_backends = (SearchFilter, OrderingFilter,)
search_fields = ('city', 'name')

def list(self, serializer, pk=None):
if pk:
queryset = models.Zone.objects.filter(city=pk)
else:
queryset = models.Zone.objects.all()
serializer = serializers.ZoneSerializer(queryset, many=True, context={'request':self.request})
return Response(serializer.data)

如何在不丢失此功能的情况下覆盖 list() 方法?

最佳答案

默认 list() 方法实现了所有这些功能。因此,不要覆盖 list,而是尝试覆盖 get_queryset() 方法。您可以使用 self.kwargs['pk'] 获取 pk 值:

class ZoneViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.IsAuthenticated,)
queryset = models.Zone.objects.all()
serializer_class = serializers.ZoneSerializer
filter_backends = (SearchFilter, OrderingFilter,)
search_fields = ('city', 'name')

def get_queryset(self):
pk = self.kwargs['pk']
if pk:
queryset = models.Zone.objects.filter(city=pk)
else:
queryset = models.Zone.objects.all()

关于python - Django Rest Framework ViewSet 在覆盖 list() 方法时丢失分页、SearchFilter 和 OrderingFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50878730/

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