简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM