To return the value of a model choice field in Django Rest Framework, you can use the source attribute in the serializer. The source attribute is used to specify the name of the attribute or method that should be used to retrieve the value from the model.

Here is an example:

# models.py
class MyModel(models.Model):
    MY_CHOICES = (
        ('A', 'Option A'),
        ('B', 'Option B'),
        ('C', 'Option C'),
    )
    my_field = models.CharField(max_length=1, choices=MY_CHOICES)

# serializers.py
class MyModelSerializer(serializers.ModelSerializer):
    my_field_display = serializers.CharField(source='get_my_field_display', read_only=True)

    class Meta:
        model = MyModel
        fields = ('id', 'my_field', 'my_field_display')

In this example, we have a MyModel with a my_field field that is a model choice field with three options. In the serializer, we have added a new field my_field_display which uses the source attribute to specify that it should use the get_my_field_display method of the model to retrieve the display value of the my_field field.

Now, when you serialize a MyModel instance using this serializer, you will get the value of the my_field_display field as the display value of the my_field field.

return model choice field value drf

原文地址: https://www.cveoy.top/t/topic/bsOM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录