Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Hassan Baig Avatar asked Dec 24 '22 06:12

Hassan Baig


1 Answers

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)
])
like image 102
user2390182 Avatar answered Dec 26 '22 20:12

user2390182