我已经研究这个问题几个小时了,但没有找到解决方案。我只是不明白。
我有一个有很多孩子的父母。我创建了一个视图,允许我获取父级的所有子级。现在我想结束该列表,并使用新的子列表对父列表进行 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
我对需要发生的事情的理解是......
- 获取提交的孩子
validated_data.pop('children')
- 循环遍历它们并将每一个添加到parent.children 多对多
- 保存父模型
我可能在这里尝试了十几种不同的想法,但我似乎无法让它发挥作用。上面的代码不会更改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"}]