使用选择序列化IntegerField的选择文本 [英] Serialise choice text for IntegerField with choices

查看:71
本文介绍了使用选择序列化IntegerField的选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化具有很多选择的模型,例如:

I'd like to serialise a model with a lot of choices like such:

class House(models.Model):
ACCESSIBILITY_CHOICES = (
    (ACCESSIBILITY_FULL, 'Full'),
    (ACCESSIBILITY_PARTIAL, 'Partial'),
    (ACCESSIBILITY_NONE, 'None')
)

accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True)

我喜欢默认的序列化程序,例如:

I love that the default serializer such as:

class HouseView(generics.ListCreateAPIView):
    model = House
    serializer_class = HouseSerializer

class HouseSerializer(serializers.ModelSerializer):

    class Meta:
        model = House

如果我只想要整数值,效果很好

works great if I want just the integer value

{accessibility:1}

但是,我想得到的是

{accessibility:'Full'}

帮助很容易非常感谢。
非常感谢。

Help is kindly appreciated. Many thanks.

推荐答案

在序列化器字段中使用诸如此类的原始值设置选择...

Set the choices in the serializer field with the raw values like so...

ACCESSIBILITY_CHOICES = (
    ('Full', 'Full'),
    ('Partial', 'Partial'),
    ('None', 'None')
)

然后看看覆盖'to_native'方法,以便将字符串值转换为它们的整数等效项。

Then take a look at overriding the 'to_native' method so that the string values get translated into their integer equivalents.

这应该为您提供一个使用字符串表示形式的外部API ,但后端使用整数表示形式。

That should give you an external API that uses the string representations, but a backend that uses the integer representations.

更新2019年: DRF现在使用不同的方法名称从内部转换为内部,请参见< a href = https://www.django-rest-framework.org/api-guide/fields/#examples rel = nofollow noreferrer>文档。为它们命名: to_representation to_internal_value ,而不是 to / from_native

Update 2019: DRF now uses different method name to convert from/to internal, see docs. to name them: to_representation and to_internal_value, instead of to/from_native.

这篇关于使用选择序列化IntegerField的选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆