Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a field editable on create and read-only on update in Django REST framework

I want to implement a kind of constant field of a Django model. I want the field to be set on create a model instance (via REST framework API), but on updating this field must be forbidden to change. Is there an elegant way to do it in Django itself or in REST framework serializer options?

like image 960
Fomalhaut Avatar asked Nov 13 '18 21:11

Fomalhaut


People also ask

What is write only field Django REST framework?

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows. write_only. Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

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.

What is Read_only field in django?

read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.


1 Answers

Overwrite the update method in the serializer and remove the field:

class MySerializer(serializers.ModelSerializer):        
    def update(self, instance, validated_data):
        validated_data.pop('myfield', None)  # prevent myfield from being updated
        return super().update(instance, validated_data)
like image 102
F.M.F. Avatar answered Oct 02 '22 16:10

F.M.F.