这两个代码有什么区别?
代码1:
class YearInSchool(models.TextChoices):
FRESHMAN = 'FR', _('Freshman')
SOPHOMORE = 'SO', _('Sophomore')
JUNIOR = 'JR', _('Junior')
SENIOR = 'SR', _('Senior')
GRADUATE = 'GR', _('Graduate')
代码2:
class YearInSchool(models.IntegerChoices):
FRESHMAN = 1, _('Freshman')
SOPHOMORE = 2, _('Sophomore')
JUNIOR = 3, _('Junior')
SENIOR = 4, _('Senior')
GRADUATE = 5, _('Graduate')
为什么每个人都使用models.TextChoices
,虽然使用models.IntegerChoices
和models.PositiveSmallIntegerField
会占用更少的内存?
我错过了一些我不太理解的东西吗?
何时使用models.TextChoices
而不是models.IntegerChoices
,反之亦然?
我问这个问题,因为在每一个django代码我正在阅读,程序员使用文本选择。我说的是一般情况,甚至是3之前的django版本。
选项的格式如下:
choice_format = (db_format, display_format)
db_format
是保存到DB的。
display_format
是调用get_<FOO>_display
时显示的内容你基本上选择保存在数据库中,整数或文本选择。问题是,当你的模型被序列化时,如果你有year
字段和YearInSchool(models.IntegerChoices):
选项,你会有这个:
"year": 1
,但是您希望它显示" freshman ",当然,如果year
是1
,您可以在序列化器级别上操作它来显示新生。
IntegerChoices
在查找时要快得多,但是它们太模糊了。如果我是您,我会每次都使用IntegerChoices,并通过序列化器操作响应,以显示文本而不是整数本身。