Django REST Framework: adding additional field to ModelSerializer

前端 未结 8 1983
遇见更好的自我
遇见更好的自我 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:05

    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.

提交回复
热议问题