在Django中,如何在模型类中将“用户组”作为外键调用? [英] In Django, How to call the 'User Group' as a foreign key in a model class?
问题描述
我创建了一个名为Question的模型类。我希望只有特定的用户组才能回答问题。现在,如何从用户组中获取外键?
I created a model class named Question. I want only particular user group can answer the questions. NOW, How can I bring a foreign key here from user group?
在我的数据库中有一个问题表。会有很多问题。但并非所有用户都可以查看或回答问题。这将取决于用户所属的用户组。因此,我必须在问题表中指定允许哪个用户组回答问题。现在,我必须在问题表中创建一个字段,我(或更具体地说是管理员)可以在其中选择用户组。为此,我必须将 Group表链接为表中的外键。
In my DB there is a Question Table. There will be a lot of questions. But not all the users are allowed to view or answer the questions. This will depend on in which user group the user belongs to. So I have to specify which user group is allowed to answer the question in the Question table. Now, I have to create a field in question table where I (or more specifically the admin) can select an user group. To do so, I have to link the "Group" table as a foreign key in the table.
from django.contrib.auth.models import Group
class Question(models.Model):
# Fields
qs_title = models.CharField(max_length=350)
qs_status = models.IntegerField()
# Relationship Fields
qs_f_track = models.ForeignKey('cmit.QuestionTrack', )
responsible = models.ForeignKey(Group) # (Is this line Okay? not working though.)
上面的代码无法正常运行添加一个说它的问题,
The above code is not working as when the admin is trying to add a question it says,
No Such Column: cmit_question.qs_f_responsible_id
推荐答案
好...得到一个解决方案...一种,就其本身...
应该是很多对很多...
让我们看一下代码...
Ok... Got a solution... Kind of, per se... The relation should be Many To Many... Lets see the code...
qs_f_group = models.ManyToManyField(Group)
qs_group = models.CharField(max_length=350, null=True)
def get_group(self):
return self.qs_f_group.all().first()
此功能是获取组的第一个条目。
非常感谢。
The function is to get the first entry of the group. Thanks a lot.
(尽管我没有使用相同的功能。但函数完全无法帮助我。 b $ b
(Though I am not using the same. A function wont help me at all. Rather I went static:
CHOICE_LIST = (('0', 'Undefined'), ('staffGroup', 'staffGroup'), ('staffGroup02', 'staffGroup02'), ('staffGroup03', 'staffGroup03'), ('staffGroup04', 'staffGroup04'), ('staffGroup05', 'staffGroup05'),)
qs_responsible = models.CharField(max_length=350, default=0, choices=CHOICE_LIST, verbose_name='Responsible Party')
不推荐,显然!
这篇关于在Django中,如何在模型类中将“用户组”作为外键调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!