Completely Lost: Many To Many with Serializers and Update in Django Rest Framework
<p>I've been looking at this for several hours now and I'm not finding the solution. I'm just not getting it.</p>

<p>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 <code>update</code> method, but I can't figure out how to make this work.</p>

<p>Here's my Child Serializer:</p>

<pre><code>class ChildSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = models.Child
        fields = ('id', 'url', 'name',)
</code></pre>

<p>Here's my Parent Serializer:</p>

<pre><code>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
</code></pre>

<p>My understanding of what needs to happen is...</p>

<ol>
<li>Get the submitted children <code>validated_data.pop('children')</code></li>
<li>Loop through them and add each one to the parent.children many to many</li>
<li>Save the parent model</li>
</ol>

<p>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.</p>

<p>Any suggestions are much welcome.</p>

<p>For reference, i've studied the following:</p>

<p><a href="http://www.django-rest-framework.org/api-guide/serializers/#saving-instances" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/serializers/#saving-instances</a></p>

<p><a href="http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations</a></p>

<p><a href="http://www.django-rest-framework.org/api-guide/serializers/#validation" rel="nofollow noreferrer">http://www.django-rest-framework.org/api-guide/serializers/#validation</a></p>

<p><a href="https://stackoverflow.com/questions/33179052/django-rest-framework-many-to-many-json-write">django rest framework many to many json write</a></p>

<p>And a bunch more but I can't remember them right now</p>

<p>UPDATE:</p>

<p>[{"id":2,"url":"<a href="http://127.0.0.1:8000/api/v1/children/2" rel="nofollow noreferrer">http://127.0.0.1:8000/api/v1/children/2</a>","first_name":"Tom","last_name":"Jones","date_of_birth"
:"1969-03-14"}]</p>