Django REST Framework: adding additional field to ModelSerializer

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

    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',
            )
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
提交回复
热议问题