gpt4 book ai didi

Django Rest框架: Limit number of fields while using serialzer as nested object

转载 作者:行者123 更新时间:2023-12-02 02:54:32 24 4
gpt4 key购买 nike

我的代码中的序列化器在两个不同的地方使用。

首次使用:直接

    class FirstSerializer(serializers.ModelSerializer):
class Meta(object):
model = FirstSerializer
fields = ('first_name', 'last_name', 'line1', 'line2',)

第二次使用:在另一个序列化器中

    class SecondSerializer(serializers.ModelSerializer):
first_serilizer = FirstSerializer(many=True, read_only=True)
class Meta(object):
model = SecondSerializer
  • 在第一个用例中,我需要所有字段。
  • 在第二个用例中,在将其用作嵌套对象时,我想从字段列表中排除“line2”。

最佳答案

我将对“FirstSerializer”类进行子类化,以限制代码重复,并仅指定“PartialFirstSerializer”上所需的字段,

class FirstSerializer(serializers.ModelSerializer):

class Meta:
model = FirstModel

class PartialFirstSerializer(FirstSerializer):

class Meta:
fields = ('first_name', 'last_name', 'line1')

class SecondSerializer(serializers.ModelSerializer):
first_serializer = PartialFirstSerializer(many=True, read_only=True)

class Meta:
model = SecondModel

如果您正在寻找更通用的解决方案,DRF 文档将向您展示如何创建采用 fields 属性的 DynamicFieldsModelSerializer。 http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""

def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)

# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)

class FirstSerializer(DynamicFieldsModelSerializer):

class Meta:
model = FirstModel

class SecondSerializer(serializers.ModelSerializer):
first_serializer = FirstSerializer(fields=('first_name', 'last_name', 'line1'), many=True, read_only=True)

class Meta:
model = SecondModel

关于Django Rest框架: Limit number of fields while using serialzer as nested object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32989716/

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