2

我做了一个这样的模型:

class Enduser(models.Model):
    user_type = models.CharField(max_length = 10)

现在我只想user_type拥有一个给定的值,比如来自['master', 'experienced', 'noob']

我可以用 Django 做到这一点吗?

另外,如何显示单选按钮列表或下拉列表/选择菜单来选择这些值之一?

4

2 回答 2

2

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!

于 2013-07-10T18:11:11.897 回答
2

Use model field choices:

CHOICES = (
    ('foo', 'Do bar?'),
    ...
)
class Enduser(models.Model):
    user_type = models.CharField(max_length = 10, choices=CHOICES)
于 2013-07-10T18:11:55.883 回答