首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否将字符串转换为IntegerChoice值?

是否将字符串转换为IntegerChoice值?
EN

Stack Overflow用户
提问于 2020-08-17 22:39:41
回答 2查看 136关注 0票数 1

假设我在模型中有一个整型字段,如下所示:

代码语言:javascript
复制
class Foo(models.Model):
    class Bar(models.IntegerChoices):
        PARROT = 1
        MESSIAH = 2
        NAUGHTY_BOY = 3
        BLACK_KNIGHT = 4

    bar = models.IntegerField(choices=Bar.choices, default=Bar.PARROT)

我如何将字符串值转换为整数来保存它,即与我使用"forms.ModelForm“上的字段作为下拉列表时发生的情况相同?例如,取"Parrot“并返回1。

代码语言:javascript
复制
from app.models import Foo
record = get_object_or_404(Foo, id=1)
record.bar = "Parrot"
record.save()

此代码给出一个错误:

代码语言:javascript
复制
Field 'bar' expected a number but got 'Parrot'.
EN

回答 2

Stack Overflow用户

发布于 2020-08-17 22:49:34

代码语言:javascript
复制
## change choice like this##


    PARROT = 1
    MESSIAH = 2
    NAUGHTY_BOY = 3
    BLACK_KNIGHT = 4
    YEAR_IN_SCHOOL_CHOICES = [
    (PARROT , 'Freshman'),
    (MESSIAH , 'Sophomore'),
    (NAUGHTY_BOY , 'Junior'),
    (BLACK_KNIGHT , 'Senior'),
    ]

## When using data, you should write it like this##

get_bar_field or html in {{get_bar_field}}
票数 0
EN

Stack Overflow用户

发布于 2020-08-18 01:08:37

您可以通过以下方式进行选择:

代码语言:javascript
复制
bar=(
    (1, PARROT)
    (2, MESSIAH)
    (3, NAUGHTY_BOY)
    (4, BLACK_KNIGHT)
)

bar = models.IntegerField (default=1, choices=bar)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63453124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档