1

Suppose I have an integer field in a model as follows:

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)

How do I convert the string value to an integer to save it i.e. the same as what appears to happen if I use the field on a "forms.ModelForm" as a drop down? E.g. Take "Parrot" and return 1.

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

This code gives an error:

Field 'bar' expected a number but got 'Parrot'.
gornvix
  • 3,154
  • 6
  • 35
  • 74

2 Answers2

0
## 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}}
sabcan
  • 407
  • 3
  • 15
0

You can do choices in this way:

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

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