问题
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?
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
回答1:
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.
(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')
Not recommended, Obviously! )
来源:https://stackoverflow.com/questions/49500232/in-django-how-to-call-the-user-group-as-a-foreign-key-in-a-model-class