如何批量更新Django查询集的多对多字段

Has*_*aig 3 python django django-models django-views

如何更新 - 批量 - Django数据模型的查询集中的多对多字段?

例如,我有一个名为的数据模型Photo,另一个名为PhotoStream.在Photo,我有which_stream = models.ManyToManyField(PhotoStream).

我提取了一个Photos被调用的查询集childhood_photos,我需要PhotoStream在这个查询集中的所有对象的多对多字段中添加一个新对象.我们称这个PhotoStream对象for_classmates.

我试试childhood_photos.update(which_stream.add(for_classmates)),但它给了我一个错误:全局名称'which_stream'没有定义.

我该怎么做这个操作?

sch*_*ggl 5

您可以通过字段的.through属性访问m2n关系的直通模型(请参阅文档).这将允许您批量创建必要的直通模型实例:

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)
])
Run Code Online (Sandbox Code Playgroud)