'Any way to update a ManyToMany field via a queryset?

Suppose I have an object:

survey = Survey.objects.all().first()

and I want to create a relationship between it and a group of objects:

respondents = Respondent.objects.all()

for r in respondents:
    r.eligible_for.add(survey)

where eligible_for is an M2M field in the Respondent model.

Is there any way to do it in one pass, or do I need to loop over the queryset?

models.py

class Questionnaire(models.Model):
    label = models.CharField(max_length=48)
    organization = models.ForeignKey('Home.Organization', on_delete=models.PROTECT, null=True)

class Respondent(models.Model):
    user = models.OneToOneField('Home.ListenUser', on_delete=models.CASCADE)
    organization = models.ForeignKey('Home.Organization', on_delete=models.PROTECT)
    eligible_for = models.ManyToManyField('Questionnaire', related_name='eligible_users', blank=True)


Solution 1:[1]

.add(…) [Django-doc] can take a variable number of items, and will usually add these in bulk.

You can thus add all the rs with:

survey.eligible_users.add(*respondents)

We here thus add the respondents to the relation in reverse. Notice the asterisk (*) in front of respondents that will thus perform iterable unpacking.

Solution 2:[2]

https://docs.djangoproject.com/en/2.2/ref/models/relations/

survey.eligible_users.set(respondents) is another way to do this without having to unpack the list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 hancho