完全迷失:Django Rest Framework中的序列化器和更新使多对多 [英] Completely Lost: Many To Many with Serializers and Update in Django Rest Framework
问题描述
我已经研究了几个小时,但没有找到解决方案。我只是不明白。
I've been looking at this for several hours now and I'm not finding the solution. I'm just not getting it.
我的父母有很多孩子。我创建了一个视图,使我可以获取父母的所有孩子。现在,我想结束该列表,并使用新的子代列表对父代执行PATCH。我知道我需要编写一个自定义的 update
方法,但是我不知道该如何做。
I have a parent that has many children. I've created a view that allows me to get all of the parent's children. Now I want to end that list and do PATCH to the parent with the new list of children. I understand that I need to write a custom update
method, but I can't figure out how to make this work.
这是我的孩子序列化器:
Here's my Child Serializer:
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
我的理解需要发生的是...
My understanding of what needs to happen is...
- 获取提交的子代
validated_data.pop('children')
- 遍历它们并将每个对象添加到parent.children多对多
- 保存父模型
我在这里可能尝试了许多不同的想法,但我似乎无法使它起作用。上面的代码不会更改children_set。
I've probably tried a dozen different ideas here, but I can't seem to get this to work. The code above doesn't change the children_set.
任何建议都是值得欢迎的。
Any suggestions are much welcome.
作为参考,我已经研究了以下内容:
For reference, i've studied the following:
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/#validation
还有很多,但我现在不记得了
And a bunch more but I can't remember them right now
更新:
[{ id:2, url: http://127.0.0.1:8000/ api / v1 / children / 2 , first_name: Tom, last_name: Jones, date_of_birth
: 1969-03-14}]
[{"id":2,"url":"http://127.0.0.1:8000/api/v1/children/2","first_name":"Tom","last_name":"Jones","date_of_birth" :"1969-03-14"}]
推荐答案
我认为您的JSON不正确。看起来应该像这样:
I think your JSON is not correct. It should look like this:
{
"id": 1,
"url": "some url",
"name": "John Smith",
"children": [
{"id": 2, "url": "child url", "name": "childs name"},
{"id": 3, ...}
]
}
这篇关于完全迷失:Django Rest Framework中的序列化器和更新使多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!