我有一个关于如何使用Django实现某些组逻辑的问题,所以这里有一张图片来帮助理解我的目标:
所以我想要的是:
如果可以实现,我还想拥有以下功能:
目前我有以下型号:
#models.py
class MyGroup(models.Model):
label = models.CharField(_('Label'), max_length=30)
members = models.ManyToManyField('MyUser', null=True, blank=True)
parents = models.ManyToManyField('self', null=True, blank=True, symmetrical=False)
# parents could be renamed to supersets/masters as well
class MyUser(AbstractBaseUser, PermissionsMixin):
subscriptions = models.ManyToManyField(
MyGroup, through=MyGroup.members.through, blank=True
)
提前感谢任何答案 - 它也有助于了解它是否真的有可能实现:然后我会知道我不会浪费时间,想办法如何去做,什么都不做。
我试着这样做:
def save(self, *args, **kwargs):
if self.parents is not None:
list_of_parents = self.parents.all()
for x in range(0, len(list_of_parents)):
new_list_of_users = list(set(list_of_parents[x].members.all()) | set(self.members.all()))
list_of_parents[x].members = new_list_of_users
super(MailingList, list_of_parents[x]).save(*args, **kwargs)
super(MailingList, self).save(*args, **kwargs)
这在某种程度上有效,但也有非常不愉快的缺陷:
"<MyGroup: group5>" needs to have a value for field "from_mygroup" before this many-to-many relationship can be used.