Django REST Framework: adding additional field to ModelSerializer

DjangoRestDjango Rest-Framework

Django Problem Overview


I want to serialize a model, but want to include an additional field that requires doing some database lookups on the model instance to be serialized:

class FooSerializer(serializers.ModelSerializer):
  my_field = ... # result of some database queries on the input Foo object
  class Meta:
        model = Foo
        fields = ('id', 'name', 'myfield')

What is the right way to do this? I see that you can pass in extra "context" to the serializer, is the right answer to pass in the additional field in a context dictionary?

With that approach, the logic of getting the field I need would not be self-contained with the serializer definition, which is ideal since every serialized instance will need my_field. Elsewhere in the DRF serializers documentation it says "extra fields can correspond to any property or callable on the model". Are "extra fields" what I'm talking about?

Should I define a function in Foo's model definition that returns my_field value, and in the serializer I hook up my_field to that callable? What does that look like?

Happy to clarify the question if necessary.

Django Solutions


Solution 1 - Django

I think SerializerMethodField is what you're looking for:

class FooSerializer(serializers.ModelSerializer):
  my_field = serializers.SerializerMethodField('is_named_bar')

  def is_named_bar(self, foo):
      return foo.name == "bar" 

  class Meta:
    model = Foo
    fields = ('id', 'name', 'my_field')

http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

Solution 2 - Django

You can change your model method to property and use it in serializer with this approach.

class Foo(models.Model):
    . . .
    @property
    def my_field(self):
        return stuff
    . . .
 
class FooSerializer(ModelSerializer):
    my_field = serializers.ReadOnlyField(source='my_field')
    
    class Meta:
        model = Foo
        fields = ('my_field',)

Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.

Solution 3 - Django

With the last version of Django Rest Framework, you need to create a method in your model with the name of the field you want to add. No need for @property and source='field' raise an error.

class Foo(models.Model):
    . . .
    def foo(self):
        return 'stuff'
    . . .
 
class FooSerializer(ModelSerializer):
    foo = serializers.ReadOnlyField()
    
    class Meta:
        model = Foo
        fields = ('foo',)

Solution 4 - Django

if you want read and write on your extra field, you can use a new custom serializer, that extends serializers.Serializer, and use it like this

class ExtraFieldSerializer(serializers.Serializer):
    def to_representation(self, instance): 
        # this would have the same as body as in a SerializerMethodField
        return 'my logic here'

    def to_internal_value(self, data):
        # This must return a dictionary that will be used to
        # update the caller's validation data, i.e. if the result
        # produced should just be set back into the field that this
        # serializer is set to, return the following:
        return {
          self.field_name: 'Any python object made with data: %s' % data
        }

class MyModelSerializer(serializers.ModelSerializer):
    my_extra_field = ExtraFieldSerializer(source='*')
    
    class Meta:
        model = MyModel
        fields = ['id', 'my_extra_field']

i use this in related nested fields with some custom logic

Solution 5 - Django

My response to a similar question (here) might be useful.

If you have a Model Method defined in the following way:

class MyModel(models.Model):
    ...

    def model_method(self):
        return "some_calculated_result"

You can add the result of calling said method to your serializer like so:

class MyModelSerializer(serializers.ModelSerializer):
    model_method_field = serializers.CharField(source='model_method')

p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:

class Meta:
    model = MyModel
    read_only_fields = (
        'model_method_field',
        )

Solution 6 - Django

If you want to add field dynamically for each object u can use to_represention.

class FooSerializer(serializers.ModelSerializer):
  class Meta:
        model = Foo
        fields = ('id', 'name',)
  
  def to_representation(self, instance):
      representation = super().to_representation(instance)
      if instance.name!='': #condition
         representation['email']=instance.name+"@xyz.com"#adding key and value
         representation['currency']=instance.task.profile.currency #adding key and value some other relation field
         return representation
      return representation

In this way you can add key and value for each obj dynamically hope u like it

Solution 7 - Django

This worked for me. If we want to just add an additional field in ModelSerializer, we can do it like below, and also the field can be assigned some val after some calculations of lookup. Or in some cases, if we want to send the parameters in API response.

In model.py

class Foo(models.Model):
    """Model Foo"""
    name = models.CharField(max_length=30, help_text="Customer Name")

In serializer.py

class FooSerializer(serializers.ModelSerializer):
    retrieved_time = serializers.SerializerMethodField()
    
    @classmethod
    def get_retrieved_time(self, object):
        """getter method to add field retrieved_time"""
        return None

  class Meta:
        model = Foo
        fields = ('id', 'name', 'retrieved_time ')

Hope this could help someone.

Solution 8 - Django

class Demo(models.Model):
    ...
    @property
    def property_name(self):
        ...

If you want to use the same property name:

class DemoSerializer(serializers.ModelSerializer):
    property_name = serializers.ReadOnlyField()
    class Meta:
        model = Product
        fields = '__all__' # or you can choose your own fields

If you want to use different property name, just change this:

new_property_name = serializers.ReadOnlyField(source='property_name')

Solution 9 - Django

As Chemical Programer said in this comment, in latest DRF you can just do it like this:

class FooSerializer(serializers.ModelSerializer):
    extra_field = serializers.SerializerMethodField()

    def get_extra_field(self, foo_instance):
        return foo_instance.a + foo_instance.b

    class Meta:
        model = Foo
        fields = ('extra_field', ...)

DRF docs source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeilView Question on Stackoverflow
Solution 1 - DjangoJ.P.View Answer on Stackoverflow
Solution 2 - DjangoWasil W. SiargiejczykView Answer on Stackoverflow
Solution 3 - DjangoGuillaume VincentView Answer on Stackoverflow
Solution 4 - DjangoMarco SilvaView Answer on Stackoverflow
Solution 5 - DjangoLindausonView Answer on Stackoverflow
Solution 6 - DjangoMajety SaiabhineshView Answer on Stackoverflow
Solution 7 - DjangoVinay KumarView Answer on Stackoverflow
Solution 8 - DjangoMd Farhan ShakibView Answer on Stackoverflow
Solution 9 - Djangotrici0paView Answer on Stackoverflow