2013-02-19 36 views
0

在我的json輸出上,我似乎沒有在我的m2m字段attribute_answers上獲取關鍵值對。請參閱下面的代碼。如何添加attribute_answers字段?Django REST M2M丟失的元數據

JSON

{ 
    "id": 20, 
    "name": "Jake", 
    "active": true, 
    "type": { 
     "id": 1, 
     "name": "Human", 
     "active": true, 
     "created": "2013-02-12T13:31:06Z", 
     "modified": null 
    }, 
    "user": "jason", 
    "attribute_answers": [ 
     1, 
     2 
    ] 
} 

串行

class ProfileSerializer(serializers.ModelSerializer): 
    user = serializers.SlugRelatedField(slug_field='username') 
    attribute_answers = serializers.PrimaryKeyRelatedField(many=True) 

    class Meta: 
     model = Profile 
     depth = 2 
     fields = ('id', 'name', 'active', 'type', 'user', 'attribute_answers') 

    def restore_object(self, attrs, instance=None): 
     """ 
     Create or update a new snippet instance. 

     """ 
     if instance: 
      # Update existing instance 
      instance.name = attrs.get('name', instance.name) 
      instance.active = attrs.get('active', instance.active) 
      instance.type = attrs.get('type', instance.type) 
      instance.attribute_answers = attrs.get('attribute_answers', instance.attribute_answers) 
      return instance 

     # Create new instance 
     return Profile(**attrs) 

回答

2

如果我理解你的問題正確,你想有一個Nested Relationship。在你ProfileSerializer,你會想:

attribute_answers = AttributeAnswerSerializer(many=True) 

這將顯示每個相關attribute_answer模型的所有屬性,給你這樣的:

{ 
    "id": 20, 
    "name": "Jake", 
    "active": true, 
    "type": { 
     "id": 1, 
     "name": "Human", 
     "active": true, 
     "created": "2013-02-12T13:31:06Z", 
     "modified": null 
    }, 
    "user": "jason", 
    "attribute_answers": [ 
     {"id": 1, "foo": "bar"}, 
     {"id": 2, "foo": "bar2"} 
    ] 
}