我的代码中的序列化程序在两个不同的地方使用。
首次使用:直接
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
答案 0 :(得分:4)
我将继承' 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