I want to create a new record in database, I set a model like below:
class FooModel(models.Model)
subject_key= models.CharField(max_length=2)
subject= modeels.CharField(max_length=100)
What I want to do is this: field 'subject_key' should be given by the client, and using the subject_key, the server will find value 'subject' and put it in the database.
So I tried to use ModelSerializer to create a new record.
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = FooModel
def get_subject(self, obj):
if obj.subject == 'SO':
return 'Stack Overflow'
else:
return 'Nothing in here'
and main running code inside view rest api is:
class FooView(APIView):
def post(self, request, *args, **kwargs):
serializer = FooSerializer(data=request.data)
if serializer.is_valid(raise_exception=True)
serializer.save()
foo = serializer.data
I checked it successfully create a new record in database, but the new record has NULL with the column 'subject'
What should I do to dynamically set the field value inside serializer?
you declare your subject field in serializer as method field, it always read only ( serializermethodfield ), you can rename your filed for example:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = FooModel
def get_var_subject(self, obj):
in this way you will have tree fields in your seriaizer 'subject', 'subject_key', 'var_subject'
OR you can add your mehod to the model and use to_representation
def to_representation(self, instance):
representation = super(FooSerializer, self).to_representation(instance)
representation['subject'] = instance.get_subject()
return representation
OR use field to_representation example for related filed but i hope you can use it
OR you need to override save
method
you can try this
def post(self, request, *args, **kwargs):
request.data['subject_key'] = request.data['subject']
serializer = FooSerializer(data=request.data)
if serializer.is_valid(raise_exception=True)
serializer.save()
foo = serializer.data
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.