我會繼承了「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框架? - 嵌套ModelSerializer查詢集限定]的可能的複製(http://stackoverflow.com/questions/25312987/django-rest-framework-limited-queryset-for-nested- modelserializer) – GwynBleidD
您必須指定'FirstSerializer'上的字段來限制字段,默認情況下,DRF modelserializer將序列化整個模型。 http://www.django-rest-framework.org/api-guide/serializers/#modelserializer –
@GwynBleidD這個問題是關於限制querryset不是字段。 –