在Django Rest框架中为嵌套序列化器过滤查询集

时间:2018-10-10 06:27:13

标签: python django django-rest-framework

这是我的观点:

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

这是我的序列化器:

class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
    model = GroupProfile
    fields = ('title','slug',)



class DepartmentSerializer(serializers.ModelSerializer):
    organizations = OrganizationSerializer(many=True, read_only=True)
    class Meta:
        model = DepartmentModel
        fields = ('title', 'organizations',)


class SectorSerializer(serializers.ModelSerializer):
    # title = serializers.CharField()
    departments = DepartmentSerializer(many=True, read_only=True)

    class Meta:
        model = SectorModel
        fields = ('title','departments',)

看,这里'SectorSerializer'是父级,' DepartmentSerializer '是子级,而<< strong> OrganizationSerializer '是大子级序列化器。现在,在我看来,我可以轻松地为“ SectorModel ”过滤查询集。但是如何过滤“ GroupProfile ”模型。

1 个答案:

答案 0 :(得分:0)

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

您可以根据 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_class。

1-子类ListSerializer,覆盖to_representation,然后调用super

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

与您的代码有关:

class FilteredListSerializer(serializers.ListSerializer):

def to_representation(self, data):
    data = data.filter(user=self.request.user, edition__hide=False)
    return super(FilteredListSerializer, self).to_representation(data)


class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
    list_serializer_class = FilteredListSerializer
    model = GroupProfile
    fields = ('title','slug',)



class DepartmentSerializer(serializers.ModelSerializer):
    organizations = OrganizationSerializer(many=True, read_only=True)
    class Meta:
        model = DepartmentModel
        fields = ('title', 'organizations',)


class SectorSerializer(serializers.ModelSerializer):
    # title = serializers.CharField()
    departments = DepartmentSerializer(many=True, read_only=True)

    class Meta:
    model = SectorModel
    fields = ('title','departments',)