Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - How to add custom field in ModelSerializer

I created a ModelSerializer and want to add a custom field which is not part of my model.

I found a description to add extra fields here and I tried the following:

customField = CharField(source='my_field') 

When I add this field and call my validate() function then this field is not part of the attr dict. attr contains all model fields specified except the extra fields. So I cannot access this field in my overwritten validation, can I?

When I add this field to the field list like this:

class Meta:     model = Account     fields = ('myfield1', 'myfield2', 'customField') 

then I get an error because customField is not part of my model - what is correct because I want to add it just for this serializer.

Is there any way to add a custom field?

like image 504
Ron Avatar asked Jan 29 '13 13:01

Ron


People also ask

How do you pass extra context data to Serializers in Django REST framework?

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.

How do you make a field optional in a serializer?

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.


1 Answers

In fact there a solution without touching at all the model. You can use SerializerMethodField which allow you to plug any method to your serializer.

class FooSerializer(ModelSerializer):     foo = serializers.SerializerMethodField()      def get_foo(self, obj):         return "Foo id: %i" % obj.pk 
like image 145
Idaho Avatar answered Sep 21 '22 13:09

Idaho