python - 过滤 Action 装饰器 - Django Rest Framework

标签 python django django-rest-framework django-filter

我正在尝试使用 Django Rest Framework 上的装饰器操作来过滤数据,如果我使用全局查询集(get_queryset() 函数),它会完美运行,但我需要在单独的函数中使用它。

我正在使用 django-filter 来执行它。这是代码。

我的看法:

class ShippingAPI(viewsets.ModelViewSet):
    serializer_class = ShippingSerializer
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('origin__department', 'destination__department', 'first_collection_date', 'last_collection_date', 'vehicle')

覆盖( Action )

@action(detail=False, methods=['GET'])
def filter_shippings(self, request, **kwargs):
    queryset = Shipping.objects.filter(status=2, orderStatus=0)
    serializer = SearchShippingSerializer(queryset, many=True) #Yes, I am using another serializer, but it is solved,I use diferent if it is necesary
    return Response(serializer.data)

在使用我的 url“api/filter_shipping/(这里是所有过滤器)”之后,这仍然会返回所有没有我请求的过滤器的数据。

谢谢你的帮助

最佳答案

像这样添加 filter_queryset 函数。它对我有用。 在 Django-filters 问题中找到解决方案:https://github.com/carltongibson/django-filter/issues/967 .

@action(detail=False, methods=['GET'])
def filter_shippings(self, request, **kwargs):
    queryset = self.filter_queryset(self.get_queryset()).filter(status=2, orderStatus=0)
    serializer = SearchShippingSerializer(queryset, many=True) #Yes, I am using another serializer, but it is solved,I use diferent if it is necesary
    return Response(serializer.data)

关于python - 过滤 Action 装饰器 - Django Rest Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368144/

相关文章:

python - 如何在 Pandas 的持续时间计算中排除周末和节假日

python - Tensorflow Inception V3 无法加载计算图

android - 使用 picasso 加载时图像未保存到存储中

python - 如果i引用的表中没有pk,如何创建新的pk

python - 将 stdin 输入重定向到 python 中线程进程的文件

python - 为什么标准 input() 会导致 EOF 错误

django - Matplotlib 和 WSGI/mod_python 不能在 Apache 上运行

python - django request.POST 包含<无法解析>

rest - 是不是rest API路由按权限分开比较好?

python - Django rest framework 如何序列化字符串列表?