假设我在模型中有一个整型字段,如下所示:
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。
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'.发布于 2020-08-17 22:49:34
## 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}}发布于 2020-08-18 01:08:37
您可以通过以下方式进行选择:
bar=(
(1, PARROT)
(2, MESSIAH)
(3, NAUGHTY_BOY)
(4, BLACK_KNIGHT)
)
bar = models.IntegerField (default=1, choices=bar)https://stackoverflow.com/questions/63453124
复制相似问题