Django:创建多项选择字段的最佳方法 [英] Django: Best way to create a multiple choice field

查看:100
本文介绍了Django:创建多项选择字段的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中创建多选选项时,似乎有两种不同的选择方式-选项a或选项b,请参见下文。每种选择相对于其他都有哪些优势。一个人通常比另一个人好吗?我是否缺少更好的方法?

WHen creating a multiple choice option in Django, there seems to be two different ways to do it - option a or option b, see below. What advantages do each option have over the other. Is one generally better than another? Am I missing a better way to do it?

选项a

TYPE_CHOICES=(
    ('teacher', ("Teacher")),
    ('student', ("Student")),
)
user_type  = models.CharField(max_length=20, default='student', choices=TYPE_CHOICES)

选项b

TYPE_CHOICES=(
    (1, ("Teacher")),
    (2, ("Student")),
)
user_type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, default=1) 


推荐答案

在过去,内存和存储的每个字节都很宝贵,将这些选择存储为小整数是有意义的,但现在并没有真正的实际好处。将其存储为字符串可使代码更具可读性,使数据库更易于管理且更易于迁移。因此,除非您真正关心存储成本的微小差异,否则我建议使用字符串作为选项值。

In the old days when every byte of memory and storage was precious storing these choices as small integers made sense, but now it has no real tangible benefit. Storing it as strings makes the code more readable, makes the database more manageable and more easily migratable. I would therefore advise using strings as option values unless you really care about the small difference in storage costs.

这篇关于Django:创建多项选择字段的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆