将字符串转换为整数选择值?

2024-05-26 14:21:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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”上的字段作为下拉列表时出现的情况相同?例如,取“鹦鹉”并返回1

from app.models import Foo
record = get_object_or_404(Foo, id=1)
record.bar = "Parrot"
record.save()

此代码给出一个错误:

Field 'bar' expected a number but got 'Parrot'.

Tags: 模型modelfoomodelsbar数字recordclass
2条回答
## 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}}

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

bar=(
    (1, PARROT)
    (2, MESSIAH)
    (3, NAUGHTY_BOY)
    (4, BLACK_KNIGHT)
)

bar = models.IntegerField (default=1, choices=bar)

相关问题 更多 >

    热门问题