Neil
Neil

Reputation: 7202

Django REST Framework: adding additional field to ModelSerializer

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.

Upvotes: 226

Views: 201995

Answers (12)

J.P.
J.P.

Reputation: 3394

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, instance):
      return instance.name == "bar" 

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

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

Upvotes: 327

O-9
O-9

Reputation: 1769

This thing took me a few hours to figure out - I wanted to group bunch of model fields together as read-only field (nest them), in my case some opening hours - that is 14 fields in total.

I used the accepted answers approach (SerializerMethodField). In that method I call another plain Serializer that serializes all the fields.

Now the problem was, because I had the instance existing I needed to use parameter instance instead of data. So my full code is:

schedule = serializers.SerializerMethodField()    

    # ...

    def get_schedule(self, obj):
        ser = ScheduleSerializer(instance=obj)  # <----- !!! not data=obj
        if ser.is_valid(raise_exception=True):
            return ser.data

(Now the question is, is this even wise thing to do, but at least I figured this out)

Used versions: Django 5.0.6 and djangorestframework 3.15.2

Upvotes: 0

Yash
Yash

Reputation: 7064

Add the following in serializer class:

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['package_id'] = "custom value"
    return representation

Upvotes: 0

Limtis
Limtis

Reputation: 115

Even though, this is not what author has wanted, it still can be considered useful for people here:

If you are using .save() ModelSerializer's method, you can pass **kwargs into it. By this, you can save multiple dynamic values.

i.e. .save(**{'foo':'bar', 'lorem':'ipsum'})

Upvotes: 2

Majety Saiabhinesh
Majety Saiabhinesh

Reputation: 311

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

Upvotes: 10

Md Farhan Shakib
Md Farhan Shakib

Reputation: 41

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')

Upvotes: 3

Vinay Kumar
Vinay Kumar

Reputation: 1307

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.

Upvotes: 5

Marco Silva
Marco Silva

Reputation: 679

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

Upvotes: 19

trici0pa
trici0pa

Reputation: 13

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

Upvotes: 0

Guillaume Vincent
Guillaume Vincent

Reputation: 14791

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',)

Upvotes: 16

Wasil W. Siargiejczyk
Wasil W. Siargiejczyk

Reputation: 813

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.

Upvotes: 57

Lindauson
Lindauson

Reputation: 3421

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',
        )

Upvotes: 12

Related Questions