Django REST Framework: adding additional field to ModelSerializer

前端 未结 8 1987
遇见更好的自我
遇见更好的自我 2020-11-28 01:33

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          


        
8条回答
  •  伪装坚强ぢ
    2020-11-28 02:15

    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

提交回复
热议问题