choice的主要使用形式为[(A,B),(C,D),(E,F)]这种形式,对于有一定python了解的同学可能知道python可以采用zip的方式生成。
这里放一个简单例子:
a = ['li', 'zhao', 'dan']
b = ['1', '2', '3']
c = zip(a, b)
print(list(c))
[('li', '1'), ('zhao', '2'), ('dan', '3')]
当然直接用元祖的方式也可以使用choice
当然,还有更进一步的使用:
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in {self.JUNIOR, self.SENIOR}
这其中YEAR_IN_SCHOOL_CHOICES中前面一个FRESHMAN表示放在数据库中的值,后面一个则表示显示值,由于FRESHMAN长度问题,我们往往采用enum的形式将键长缩短为几个字符来进行存储。
跟进一步,就和django自己定义的类有关了
class NIHAO(model.Models)
class YearInSchool(models.TextChoices):
FRESHMAN = 'FR', _('Freshman')
SOPHOMORE = 'SO', _('Sophomore')
JUNIOR = 'JR', _('Junior')
SENIOR = 'SR', _('Senior')
GRADUATE = 'GR', _('Graduate')
Textchoices可以写成内置类,将上述内容转换成该代码
而对于整数类,可以采用:
class Card(models.Model):
class Suit(models.IntegerChoices):
DIAMOND = 1
SPADE = 2
HEART = 3
CLUB = 4
通过django官方文档我们可以继续进行后续学习https://docs.djangoproject.com/en/4.0/ref/models/fields/