Hassan Baig Hassan Baig - 2 years ago 243
Python Question

How to bulk update the many-to-many field of a Django queryset

How does one update - in bulk - a many to many field in the queryset of a Django data model?

For instance, I have a data model called

Photo
, and another called
PhotoStream
. In
Photo
, I have
which_stream = models.ManyToManyField(PhotoStream)
.

I extracted a queryset of
Photos
called
childhood_photos
, and I need to add a new
PhotoStream
object in the many-to-many fields of all objects within this queryset. Let's call this PhotoStream object
for_classmates
.

I try
childhood_photos.update(which_stream.add(for_classmates))
, but it gives me an error: global name 'which_stream' is not defined.

How can I do this operation?

Answer Source

You can access the through model of your m2n relationship via the field's .through attribute (see the documentation). That will allow you to bulk create the necessary through model instances:

through_model = Photo.which_stream.through  # gives you access to auto-created through model
# print through_model
# <class 'app_label.models.Photo_which_stream'>  # or sth. similar

through_model.objects.bulk_create([
    through_model(photo_id=pk, photostream_id=for_classmates.pk) 
        for pk in childhood_photos.values_list('pk', flat=True)
])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download