在批量交易中将一个对象添加到许多对象的M2M字段中

时间:2018-10-09 16:21:33

标签: django

我收到以下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关系上不起作用。我有什么办法可以一口气做到这一点吗?

1 个答案:

答案 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)
相关问题