gpt4 book ai didi

python - Django Rest框架中嵌套序列化器的过滤查询集

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:42 25 4
gpt4 key购买 nike

这是我的观点:

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'是子级,'OrganizationSerializer'是孙级序列化器。现在,在我看来,我可以轻松地过滤“SectorModel”的查询集。但是我如何过滤“GroupProfile”模型。

最佳答案

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

您可以通过根据 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 添加为嵌套序列化器元上的 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',)

关于python - Django Rest框架中嵌套序列化器的过滤查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733905/

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