完全丢失:Django Rest Framework 中的序列化器和更新的多对多

2024-04-22

我已经研究这个问题几个小时了,但没有找到解决方案。我只是不明白。

我有一个有很多孩子的父母。我创建了一个视图,允许我获取父级的所有子级。现在我想结束该列表,并使用新的子列表对父列表进行 PATCH。我明白我需要写一个自定义update方法,但我不知道如何使其工作。

这是我的子序列化器:

class ChildSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = models.Child
        fields = ('id', 'url', 'name',)

这是我的父序列化器:

class ParentSerializer(serializers.HyperlinkedModelSerializer):
    children = ChildSerializer(many=True)

    class Meta:
        model = models.Parent
        fields = ('id', 'url', 'name', 'children',)

    def update(self, instance, validated_data):
        submitted_children = validated_data.get('children')
        if submitted_children:
            for child in submitted_children:
                child_instance = Child.objects.get(id=child.id)
                instance.children.add(child_instance)
        instance.save()
        return instance

我对需要发生的事情的理解是......

  1. 获取提交的孩子validated_data.pop('children')
  2. 循环遍历它们并将每一个添加到parent.children 多对多
  3. 保存父模型

我可能在这里尝试了十几种不同的想法,但我似乎无法让它发挥作用。上面的代码不会更改children_set。

任何建议都非常受欢迎。

作为参考,我研究了以下内容:

http://www.django-rest-framework.org/api-guide/serializers/# saving-instances http://www.django-rest-framework.org/api-guide/serializers/#saving-instances

http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations

http://www.django-rest-framework.org/api-guide/serializers/#validation http://www.django-rest-framework.org/api-guide/serializers/#validation

django Rest框架多对多json写入 https://stackoverflow.com/questions/33179052/django-rest-framework-many-to-many-json-write

还有很多,但我现在记不起来了

UPDATE:

[{“id”:2,“网址”:“http://127.0.0.1:8000/api/v1/children/2 http://127.0.0.1:8000/api/v1/children/2","first_name":"汤姆","last_name":"琼斯","date_of_birth" :"1969-03-14"}]


我认为你的 JSON 不正确。它应该看起来像这样:

{
 "id": 1,
 "url": "some url",
 "name": "John Smith",
 "children": [
   {"id": 2, "url": "child url", "name": "childs name"},
   {"id": 3, ...}
 ]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

完全丢失:Django Rest Framework 中的序列化器和更新的多对多 的相关文章

随机推荐