I have a model with choices attribute like this:
commonness_choices = (
("1", "very uncommon"),
("2", "uncommon"),
("3", "common"),
("4", "very common"),
)
class Event(models.Model):
commonness = models.CharField(max_length=30, choices=commonness_choices)
When I try to use Event.commonness in views.py, it uses the second element of each choice tuple. For example, if I do this:
event = Event.objects.get(pk=1)
event.commonness = "uncommon"
event.commonness is set to ("2", "uncommon"). When event.commonness is used, it uses the second element, "uncommon", instead of the first element, "2". Is there a way to select and use the first element of tuple? I wish to use both the first element and the second element of tuple in different cases.
I would setup your choices like this:
class Event(models.Model):
VERY_UNCOMMON = 0
UNCOMMON = 1
COMMON = 2
VERY_COMMON = 3
COMMONNESS_CHOICES = (
(VERY_UNCOMMON, _('Very Uncommon')),
(UNCOMMON, _('Uncommon')),
(COMMON, _('Common')),
(VERY_COMMON, _('Very Common')),
(CANCELED, _('Canceled')),
)
commonness_choices = models.IntegerField(
choices=COMMONNESS_CHOICES, default=VERY_UNCOMMON)
For example, whenever you want to call the number, you can do Event.VERY_UNCOMMON
. That will return 0
(the first element).
Does that make sense?
I changed the code so that event.commonness sets to "2" and used event.get_commonness_display() to view the second element of tuple. And it works as I want it to. Thank you for help in comments!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.