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?
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.
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.
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.
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.
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)
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