Django:如何获取用户组列表并将该列表(字典)用作模型字段的选择选项?

Django: How to get the list of the usergroups and use that list (dictionary) as a choice options for a model field?

场景

我的模型“问题”中有一个名为“编辑器”的字段,如下所示:

CHOICE_LIST = (('0', 'Undefined'), ('staffGroup', 'staffGroup'), ('staffGroup02', 'staffGroup02'), ('staffGroup03', 'staffGroup03'), ('staffGroup04', 'staffGroup04'), ('staffGroup05', 'staffGroup05'),)
editor = models.CharField(max_length=350, default=0, choices=CHOICE_LIST, verbose_name='Responsibility')

编辑器字段有一个选择列表,我根据用户组的名称手动定义了该列表。

问题:

  1. 如何直接从 auth_grup table 生成列表?
  2. 我如何有选择地做到这一点(因为我可能不需要所有这些,我可能只需要那些以 'staff' 字符串开头的组)
  3. 我怎样才能使这个列表静态(因此从用户组中删除条目可能不会从列表中删除它) dynamic(会随着 auth_group table 中的变化动态更新列表)?

回复 1:您可以使用 returns 所有组的可调用项。示例:

def getGroupNames():
    return Group.objects.all().values_list('name', flat=True)

您仍然需要将其转换为 ('short-name', 'human-readable-name')

的元组

如果你想在元组中使用与人类可读的简短名称相同的全名,你可以这样做:

def getGroupNames():
    groups = Group.objects.all().values_list('name', flat=True)
    return zip(groups, groups)

然后在选择字段中使用相同的

editor = models.CharField(max_length=350, default=0, choices=getGroupNames(), verbose_name='Responsibility')

回复 2:您可以过滤查询

def getGroupNames():
    return Group.objects.filter(name__starts_with='staff').values_list('name', flat=True)

Using choices is a presentation convenience. There is no restriction of the value that can be sent to the database, even coming from the front-end. For example, if you use the browser's inspect feature, you can edit the drop-down list, change one of the values and submit it. The back-end view will then happily consume it and save it to the database.

意味着您仍然可以这样做

obj = SomeModel.objects.get(pk=1)
obj.editor = 'Random Value not part of choices'
obj.save()

回复3:上面提到的可调用技术是静态的还是动态的,就看你怎么写了;当您进行迁移时,将评估此功能,并且这些值将作为选项添加到迁移文件中。但是,您围绕此模型编写的任何序列化程序或表单都会一次又一次地评估选择。

参考:https://zindilis.com/blog/2017/05/04/django-backend-validation-of-choices.html