Totally lost: many for many with serializers and an update in the Django Rest Framework

I have been looking at this for several hours, and I cannot find a solution. I just do not understand.

I have a parent who has many children. I created a view that allows me to get all the parent children. Now I want to finish this list and make a PATCH for parents with a new list of children. I understand that I need to write my own update method, but I cannot figure out how to do this.

Here is my child serializer:

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

Here is my parent serializer:

 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 is about to happen is ...

  • Get sent children validated_data.pop('children')
  • Scroll through them and add each one to parent.children many to many
  • Save Parent Model

I probably tried a few dozen different ideas here, but I can't get it to work. The above code does not change children_set.

Any suggestions are welcome.

For reference, I 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

django rest framework a lot for many json write

And a bunch more, but I can’t remember them right now

UPDATE:

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

+5
source share
1 answer

I think your JSON is incorrect. It should look like this:

 { "id": 1, "url": "some url", "name": "John Smith", "children": [ {"id": 2, "url": "child url", "name": "childs name"}, {"id": 3, ...} ] } 
+2
source

Source: https://habr.com/ru/post/1244759/


All Articles