NirIzr NirIzr - 9 months ago 62
Python Question

Django rest framework create-only serializer field

I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients.

This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object this task has started running on).

I was hoping for something similar to

, so I could have something similar to:

class TaskSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
task_id = serializers.ReadOnlyField()
target_object = serializers.CreateOnlyField()

but couldn't find it in the documentation or google.

wim wim
Answer Source

This is the responsibility of the viewset, not the serializer. The idea of a CreateOnlyField on a serializer doesn't make much sense.

On your view, you'll have to configure the POST request but lock down PUT and PATCH requests the way you want.