我正在 Django 中开发一个项目,但遇到以下问题:
我有这两个类,团队和项目。当我创建一个项目时,我想自动将团队中的用户分配给我在创建项目时选择的新项目。我覆盖了项目的保存方法,并在创建项目后将用户分配给项目(我在保存后做了,因为之前给了我一个错误)。我尝试了几种方法,但没有一种方法有效。试用者:
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()
谢谢您的帮助