Django rest fram中嵌套序列化程序的筛选器查询集

2024-10-04 01:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的观点:

class SectorListAPI(generics.ListAPIView):
    queryset = SectorModel.objects.all()
    serializer_class = SectorSerializer

这是我的序列化程序:

^{pr2}$

看,这里SectorSerializer'是父级'DepartmentSerializer'是子级,'OrganizationSerializer'是子级序列化器。现在在我看来,我可以很容易地过滤我的查询集来查找“SectorModel”。但是我怎样才能过滤出“GroupProfile”模型呢。在


Tags: 程序序列化objectsallclassquerysetserializer观点
1条回答
网友
1楼 · 发布于 2024-10-04 01:26:52

您可能需要过滤queryset,以确保只返回与发出请求的当前经过身份验证的用户相关的结果。在

您可以根据request.user.的值进行过滤

例如:

from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

编辑

您可以将ListSerializer子类化并覆盖to_representation方法。在

默认情况下,to_representation方法调用嵌套查询集上的data.all()。因此,您实际上需要在调用方法之前生成data = data.filter(**your_filters)。然后需要将子类ListSerializer添加为嵌套序列化程序的meta上的list_serializer_类。在

1-子类ListSerializer,重写to_representation,然后调用super

2-在嵌套序列化程序上添加子类ListSerializer作为元list_serializer_class。在

与您相关的代码:

^{pr2}$

相关问题 更多 >