Django REST Framework: adding additional field to ModelSerializer

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

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

提交回复
热议问题