How do add a non-model field on a ModelSerializer in DRF 3? i.e. add a field that does not exist on my actual model?
class TestSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='vote_detail')
non_field = serializers.CharField() # no corresponding model property.
class Meta:
model = vote_model
fields = ("url", "non_field")
def create(self, validated_data):
print(direction=validated_data['non_field'])
But DRF 3 gives me the error:
Got AttributeError when attempting to get a value for field `non_field` on serializer `TestSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Test` instance.
Original exception text was: 'Test' object has no attribute 'non_field'.
I have searched stack DRF - ModelSerializer with a non-model write_only field and found a few solutions but these refer to DRF 2 where I'm using DRF 3. Is there a solution for this on this version?
Just an example might help you.
Source: https://github.com/tomchristie/django-rest-framework/issues/951
As mentioned there are two ways. (1) adding a model property. (2) adding a model field. I feel that adding a @property to model was explained well in this post. If you want to keep your models "lean and mean" use a Method field. Chandus answer omits some crucial points, though:
get_
field_name. If you use another name use themethod_name=method
name argument onSerializerMethodField()
Source:
Django REST Framework: adding additional field to ModelSerializer
The
serializers.CharField(write_only=True)
andserializers.ListField(...)
is a good solution to provide extra data to your.create
and.update
methods, as either a single string or a list of strings (you can mixListField
with other serializer field types). With this method you can also definedef validate_write_only_char_field
to implement some quick and simple validation.serializers.SerializerMethodField()
allows you to add some custom read only field to your serializer output from a method defined on the serializer.The
read_only_custom_model_field
would use a method on your model to read some data, not strictly a model field, but a custom method. I.e.http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
or go through this link