I'd like to add a custom field to a serializer that's used when creating resources. It's not a model field.
I tried the following:
class CampaignSerializer(ModelSerializer):
class Meta:
model = Campaign
fields = ("groups",)
write_only_fields = ("groups",)
groups = ListField(IntegerField(), min_length=1)
def validate(self, data):
# ...
return data
However groups
doesn't exist in data
in the validate()
function. I found out that DRF sets read_only=True
for the field, which is definitely not what I want.
Is there a way to specify a writable field, or do I have to resort to the view set's perform_create()
method?
The following will work, but is likely not the intended way of doing it:
from rest_framework import serializers
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('foo', ) # also add your normal model fields
foo = serializers.SerializerMethodField()
def get_foo(self, obj):
return ... # do necessary reading stuff
def create(self, validated_data):
# use self.initial_data to access the raw input data sent in POST request
self.initial_data['foo']
... # do necessary validations of 'foo'
instance = super().create(validated_data)
... # do necessary write stuff
return instance
# Do likewise with .update method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.