I've been looking at this for several hours now and I'm not finding the solution. I'm just not getting it.
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',)
Here's 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 needs to happen is...
validated_data.pop('children')
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
django rest framework many to 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"}]
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
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, ...}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With