0

在我的 json 输出中,我似乎没有在我的 m2m 字段 attribute_answers 上获得键值对。请参阅下面的代码。如何在 attribute_answers 字段中添加?

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)
4

1 回答 1

2

如果我正确理解你的问题,你想要一个嵌套关系。在您的 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"}
    ]
}
于 2013-02-19T21:37:10.443 回答