djangorestdjango-rest-framework

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.


Solution

  • 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