Lets consider this model:
class MyModel(models.Model):
DEFAULT = 1
NOT_DEFAULT = 2
SOMETHING = 3
SOMETHING_ELSE = 4
CHOICES = (
(DEFAULT, 'foo')
(NOT_DEFAULT, 'bar')
(SOMETHING, 'tar')
(SOMETHING_ELSE, 'oof')
)
field1 = models.CharField(
max_length=128,
)
field2 = models.SmallIntegerField(
choices=CHOICES,
default=DEFAULT
)
how to i fill it with this data?
name, status
'one', 'foo'
'two', 'oof'
'tree', 'foo'
'four', 'foo'
'five', 'tar'
'six', 'bar'
that does not work since it's expecting an integer
MyModel.objects.create('one','foo')
how do i do it properly without stupid workarounds?
is there a build in mapping like
'foo' -> 1
'oof' -> 4
etc.?
You have the tuple of tuples CHOICES
and you need to find first element by value of the second. So you can generate dict from tuple and get value, for example:
value = 'foo'
{v: k for k, v in MyModel.CHOICES}.get(value)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments