【发布时间】:2018-12-03 19:32:23
【问题描述】:
我有 3 个模型:User、UserProfile 和 Programme。用户持有所有用户的姓名;
class User(AbstractUser):
first_name = model.Charfield(...)
last_name = model.Charfield(...)
...
UserProfile 包含与每个用户相关的属性(例如,销售经理(sm)、项目经理(pm)、交付经理(dm)等。
class UserProfile(model.Model):
user = model.ForeignKey(User, on_delete...)
sm = model.BooleanField(default = False, editable=True...)
pm = model.BooleanField(default = False, editable=True...)
dm = model.BooleanField(default = False, editable=True...)
用户可以具有 UserProfile 属性的任意组合。例如: 用户 1:sm 用户 2:sm,pm 用户 3:dm 用户 4:sm,dm ...
Program 中的每个程序都必须为每个 sm、pm 和 dm 分配一个用户,所以我的挑战是找到一种方法来为每个 sm、pm 和 dm 生成一个“选择”列表,限制为具有适当属性的用户。
class Programme(model.Models):
programme_name = models.Charfield(...)
AND ESSENTIALLY:
sm = only users with userprofile.sm = True
pm = only users with userprofile.pm = True
dm = only users with userprofile.dm = True
我尝试向 UserProfile 添加一个函数,然后在 Programme 中引用它:
UserProfile(model.Models):
....
def get_pm(self):
pm_list = []
pm = UserProfile.objects.filter(pm=True)
for i in pm:
pm_list.append(i.user.last_name)
return pm_list
在节目中:
Programme(model.Models):
pm = models.Charfield(choices=UserProfile.get_pm, ...
但这会产生错误:“选择”必须是可迭代的(例如,列表或元组)。
同样,我尝试将相同的函数添加到 Programmes/models.py,但这会产生相同的错误。
我知道我遗漏了显而易见的内容,但感谢所有帮助。
【问题讨论】:
标签: django django-models