Issue
Right now, DRF's read_only
argument on a Serializer
constructor means you can neither create nor update the field, while the write_only
argument on a Serializer
constructor allows the field to be created OR updated, but prevents the field from being output when serializing the representation.
Is there any (elegant) way to have a Serializer
field that can be created, exactly once, when the model in question is created (when the create()
is called on the Serializer
), but cannot that later be modified via update
?
NB: Yes, I've seen this solution, but honestly I find it ugly and un-Pythonic. Is there a better way?
Solution
class TodoModifySerializer(ModelSerializer):
def to_internal_value(self, data):
data = super(TodoModifySerializer, self).to_internal_value(data)
if self.instance:
# update
for x in self.create_only_fields:
data.pop(x)
return data
class Meta:
model = Todo
fields = ('id', 'category', 'title', 'content')
create_only_fields = ('title',)
you can do it in to_internal_value
method by remove this data when update
Answered By - Ykh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.