2015-10-07 66 views
1

我的代碼中的序列化程序在兩個不同的地方使用。Django Rest框架:在使用serialzer作爲嵌套對象時限制字段數

起初用途:直接

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'。
+0

[django的REST框架? - 嵌套ModelSerializer查詢集限定]的可能的複製(http://stackoverflow.com/questions/25312987/django-rest-framework-limited-queryset-for-nested- modelserializer) – GwynBleidD

+0

您必須指定'FirstSerializer'上的字段來限制字段,默認情況下,DRF modelserializer將序列化整個模型。 http://www.django-rest-framework.org/api-guide/serializers/#modelserializer –

+0

@GwynBleidD這個問題是關於限制querryset不是字段。 –

回答

2

我會繼承了「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 
+0

第二種方法的好處是什麼?根據我對分類的理解,它更易於閱讀並使事情變得簡單。 – iankit

+0

@iankit第二種方法更具活力和乾爽,如果你會在多個場合做同樣的事情。如果這是一次性的事情,我只會繼承'FirstSerializer' –