2013-02-19 5 views
0

Sur ma sortie json, il ne semble pas que j'obtiens des paires de valeurs de clés sur mon champ m2m attribute_answers. voir le code ci-dessous. Comment ajouter dans les champs attribute_answers?Django REST Méta-données pour M2M manquantes

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 
    ] 
} 

sérialiseur

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) 

Répondre

2

Si je comprends bien votre question, vous voulez un Nested Relationship. Dans votre ProfileSerializer, vous aurez envie:

attribute_answers = AttributeAnswerSerializer(many=True) 

Cela permet d'afficher tous les attributs de chaque modèle de attribute_answer associé et vous donner quelque chose comme:

{ 
    "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"} 
    ] 
} 
Questions connexes