我做了一个这样的模型:
class Enduser(models.Model):
user_type = models.CharField(max_length = 10)
现在我只想user_type
拥有一个给定的值,比如来自['master', 'experienced', 'noob']
我可以用 Django 做到这一点吗?
另外,如何显示单选按钮列表或下拉列表/选择菜单来选择这些值之一?
我做了一个这样的模型:
class Enduser(models.Model):
user_type = models.CharField(max_length = 10)
现在我只想user_type
拥有一个给定的值,比如来自['master', 'experienced', 'noob']
我可以用 Django 做到这一点吗?
另外,如何显示单选按钮列表或下拉列表/选择菜单来选择这些值之一?
You can take advantage of the choices
attribute for CharField
:
class Enduser(models.Model):
CHOICES = (
(u'1',u'master'),
(u'2',u'experienced'),
(u'3',u'noob'),
)
user_type = models.CharField(max_length = 2, choices=CHOICES)
This will save values 1,2 or 3
in the db and when retrieved the object, it will map it to master, experienced or noob
. Take a look at the docs for more info.
Hope this helps!
CHOICES = (
('foo', 'Do bar?'),
...
)
class Enduser(models.Model):
user_type = models.CharField(max_length = 10, choices=CHOICES)