Add one object to M2M fields of many objects in a bulk transaction

I've got the following post_save signal.

@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)

The idea is that once the survey is created, if it is open to everyone, it will automatically be added to their eligible_for row.

Unfortunately, update() doesn't work on M2M relationships. Is there any way I can do this in one fell swoop?

1 answer

  • answered 2018-10-09 16:33 Adam Starrh

    Given the following model:

    class Respondent(models.Model):
        user = models.OneToOneField('Home.ListenUser', on_delete=models.CASCADE)
        eligible_for = models.ManyToManyField('Questionnaire', related_name='eligible_users', null=True)
    

    I used this to accomplish it:

    @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)