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

2024-06-30 13:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

场景

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

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表生成列表?在
  2. 我如何有选择地做到这一点(因为我可能不需要所有的组,我可能只需要那些以'staff'字符串开头的组)
  3. 如何使该列表静态(因此从usergroup删除条目可能不会从列表中删除)动态(将根据auth_group表中的更改动态更新列表)?在

Tags: 模型auth列表场景动态编辑器editorlist
1条回答
网友
1楼 · 发布于 2024-06-30 13:31:14

re1:您可以使用一个返回所有组的callable。示例:

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

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

如果要在元组中使用与短名称和人类可读名称相同的全名,可以执行以下操作:

^{pr2}$

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

^{3}$

回复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()

Re3:上面提到的可调用技术是静态的还是动态的,正如您编写的那样;当您进行迁移时,将对该函数进行求值,并将这些值作为选项添加到迁移文件中。但是,围绕此模型编写的任何序列化程序或表单都会一次又一次地评估选择。在

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

相关问题 更多 >