如何在django rest框架中自动显示一个模型属性的值而不是键?

drkbr07n  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(118)

我有一个带有模型属性的DRF API,选择字段如下所示:

STRONG_FOOT = (
    ("N", "-"),
    ("R", "Right"),
    ("L", "Left"),
    ("B", "Both")
)

class Player(models.Model):
    ...
    strong_foot = models.CharField(max_length=2, choices=STRING_FOOT)
    ...

我可以选择在我的序列化器中显示值而不是键,如下所示:

class JoueurSerializer(serializers.ModelSerializer):
    ...
    strong_foot = serializers.CharField(source="get_strong_foot_display")
    ...
    class Meta:
        model = Player
        fields = "__all__"

我遇到的问题是,我的模型中有30多个属性。有没有办法让DRF在列表视图中自动显示选择字段的值而不是键?还是我需要对所有属性执行序列化器中的操作?

ruarlubt

ruarlubt1#

使用任何带有选项的字段,无需在序列化程序中为每个字段指定自定义方法:

from rest_framework import serializers

class ChoicesSerializerField(serializers.SerializerMethodField):
    """
    A read-only field that return the representation of a model field with choices.
    """

    def to_representation(self, value):
        # sample: 'get_XXXX_display'
        method_name = 'get_{field_name}_display'.format(field_name=self.field_name)
        # retrieve instance method
        method = getattr(value, method_name)
        # finally use instance method to return result of get_XXXX_display()
        return method()

相关问题