In Django, How to call the 'User Group' as a foreign key in a model class?

淺唱寂寞╮ 提交于 2020-01-01 17:25:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!