I want to serialize a model and include extra field. I want use this serializer for list, detail and create views. In serialializer I use create, update, and get_field methods to customize logic.
class ExampleSerializer(serializers.ModelSerializer):
field = serializers.CharField()
class Meta:
model = Example
fields = ("field", ...)
When I add new object everything is correct (I can validation custom field data), but when I get object, 'field' don't exists in response.
EDIT: I want set custom method on serializer class to get field. This is better logic solution for me then set custom method on model.
Why is it like that? Is exist better solution for this (I don't want use SerializerMethodField)?
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.
By default it is set to False. Setting it to True will allow you to mark the field as optional during "serialization". Note: required property is used for deserialization.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
The field is not part of the model, due to that it is coming the error. You can make that field write_only=True.Suppose field is extra field.
class ExampleSerializer(serializers.ModelSerializer):
field = serializers.CharField(write_only=true)
class Meta:
model = Example
fields = ("field", ...)
or you can give the source value the field cross ponds to which field.
We can define the property method with that field name. You can include that field in the serializer as read only any data you can return for that
class Example(model.MOdels):
@property
def field(self):
return #whatever you want to return
you can use serilizermethod field .
class ExampleSerializer(serializers.ModelSerializer):
field = serializers.serializerMethod()
class Meta:
model = Example
fields = ("field", ...)
def get_field(self, obj):
return obj.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