我收到以下post_save
信号。
@receiver(post_save, sender=Questionnaire)
def add_new_eligible_users_to_questionnaire(sender, instance, created, **kwargs):
if created:
if instance.open_to_all:
users = Respondent.objects.filter(organization=instance.organization)
users.update(eligible_for=instance)
想法是,一旦创建了调查表,并且对所有人开放,它将自动添加到他们的eligible_for
行中。
不幸的是,update()
在M2M关系上不起作用。我有什么办法可以一口气做到这一点吗?
答案 0 :(得分:0)
给出以下模型:
class Respondent(models.Model):
user = models.OneToOneField('Home.ListenUser', on_delete=models.CASCADE)
eligible_for = models.ManyToManyField('Questionnaire', related_name='eligible_users', null=True)
我用它来完成它:
@receiver(post_save, sender=Questionnaire)
def add_new_eligible_users_to_questionnaire(sender, instance, created, **kwargs):
if created:
if instance.open_to_all:
users = Respondent.objects.filter(organization=instance.organization)
instance.eligible_users.set(users)