gpt4 book ai didi

Django 序列化程序继承和扩展字段

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

我有这两个序列化程序:

class BasicSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('lengthy', 'touple', 'of', \
'fields', 'like', '10', 'of', 'them')

class AdvandedSerializer(BasicSerializer):
additional_field = serializers.SerializerMethodField()
def get_additional_field(self, obj):
return('not important')
class Meta:
model = MyModel
fields = ('lengthy', 'touple', 'of', \
'fields', 'like', '10', 'of', 'them', 'additional_field')

这显然是相当丑陋的代码。我想获取并扩展 fields来自 super() ,但是我不知道如何。

最佳答案

你可以做:

class BasicSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('lengthy', 'touple', 'of', 'fields', 'like', '10', 'of', 'them')

class AdvandedSerializer(BasicSerializer):
additional_field = serializers.SerializerMethodField()

def get_additional_field(self, obj):
return('not important')

class Meta(BasicSerializer.Meta):
fields = BasicSerializer.Meta.fields + ('additional_field',)

关于Django 序列化程序继承和扩展字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49900629/

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