我正在Django开展一个项目,我遇到了以下问题:
我有两个班,团队和项目。当我创建一个项目时,我想自动为团队中的用户分配在创建项目到新项目时选择的内容。 我重写了Project的save方法,在创建项目后,将用户分配给项目(保存后我做了,因为之前给了我一个错误)。我试过几种方法,但没有一种方法有效。 试过:
self.user.add(*self.team.users.all())
self.save()
这不起作用。
尝试迭代:
for uTeam in self.team.users.all():
self.users.add(uTeam)
并且也无效。
对我来说唯一有效的方法就是这个,但只在Django Shell中使用:
P = Project.objects.get(pk=1)
T = Team.objects.get(pk=1)
P.user.add(*T.user.all())
P.save()
这是我在下面的解决方案,但在Django中不起作用(给出无限循环)
class Team(models.Model):
name = models.CharField(max_length=200,
help_text=_('name of the team'))
user = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name="members_of_team",
help_text=_('users of the team'),
null=True
)
and more....
class Project(models.Model):
id = models.AutoField(primary_key=True, null=False)
name = models.CharField(max_length=200,
help_text=_('name of project'),
)
team = models.ForeignKey(Team,`enter code here`
on_delete=models.PROTECT,
help_text=_('team of project'))
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name='creator_project',
blank=True,
null=False,
help_text=_('project created by'))
customer = models.ForeignKey(Customer,
on_delete=models.PROTECT,
help_text=_('customer'))
user = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='users_team',
blank=True,
null=False,
help_text=_('users of this project'))
def save(self, *args, **kwargs):
if self.checkIntegrity():
super(Project, self).save(*args, **kwargs)
if self.user.all().count() < self.team.user.all().count():
T = Team.objects.get(pk=self.team.id)
P = Project.objects.get(pk=self.id)
P.user.add(*T.user.all())
P.save()
感谢您的帮助
答案 0 :(得分:0)
我明白了,我读到在save()和post_save()之后填充了m2m字段,并且当m2m字段发生变化时会触发一个信号,所以我写下以下内容:
@receiver(m2m_changed, sender=Project.user.through)
def m2mChange(sender, **kwargs):
instance = kwargs['instance']
T = Team.objects.get(pk=instance.team.id)
if kwargs['pk_set'] is None:
instance.user.add(*T.user.all())
现在它工作正常。 谢谢大家。