[Fixed]-ModelViewSet – Update nested field

8πŸ‘

A little late, but, Try this,

class OwnerSerializer(serializers.ModelSerializer):
    class Meta:
        model =  Owner
        fields = ('id', 'name')
        extra_kwargs = {
            'id': {
                'read_only': False, 
                'required': True
             }
        } #very important

    def create(self, validated_data):
        # As before.
        ...

    def update(self, instance, validated_data):
        # Update the  instance
        instance.some_field = validated_data['some_field']
        instance.save()

        # Delete any detail not included in the request
        owner_ids = [item['owner_id'] for item in validated_data['owners']]
        for owner in cars.owners.all():
            if owner.id not in owner_ids:
                owner.delete()

        # Create or update owner 
        for owner in validated_data['owners']:
            ownerObj = Owner.objects.get(pk=item['id'])
            if ownerObje:
                ownerObj.some_field=item['some_field']
                ....fields...
            else:
               ownerObj = Owner.create(car=instance,**owner)
            ownerObj.save()

        return instance
πŸ‘€Erick lxvi

2πŸ‘

Just in-case someone stumbles on this

had the same error in my case but setting read_only to True fixed it for me.

    owner = ownerSerializer(many=False, read_only=True) 

Note that, this field won’t appear in the form when posting data to the api.

πŸ‘€pycod333

Leave a comment