[英]Django multiple choices for an attribute model
I've got a model Post: 我有一个模型帖子:
class Post(models.Model):
# Each post can only have one author.
author = models.ForeignKey(User, related_name='poster')
INTRODUCTION = 'I'
STORIES = 'S'
CATEGORY_CHOICES = (
(STORIES, 'Stories'), # Variable name and display value
(INTRODUCTION, 'Introduce Yourself'),
)
category = models.CharField(max_length=1,
choices=CATEGORY_CHOICES,
default=INTRODUCTION)
#Add votes attribute in order to get a total reputation per user based on votes per post.
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.title
I have tried to create an instance of Post: 我试图创建一个Post实例:
post = Post.objects.create(
author = user,
category = 'STORIES',
)
but when I check the admin page it is not registered under the Stories category. 但是当我检查管理页面时,它没有在“故事”类别下注册。 Am I assigning the category wrongly? 我是否错误地分配了类别?
You need to specify S
(the first element of tuple; the actual value to be set in the model), not Stories
(the second element of tuple; the human-readable name). 您需要指定S
(元组的第一个元素;要在模型中设置的实际值),而不是Stories
(元组的第二个元素;人类可读的名称)。
post = Post.objects.create(
author=user,
category='S' # or Post.STORIES
)
See choices
- Model field reference - Django documentation 查看choices
-模型字段参考-Django文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.