【问题标题】:How to bulk update the many-to-many field of a Django queryset如何批量更新 Django 查询集的多对多字段
【发布时间】:2016-08-17 18:38:42
【问题描述】:

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

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

我提取了一个名为childhood_photosPhotos 查询集,我需要在该查询集中所有对象的多对多字段中添加一个新的PhotoStream 对象。我们称这个 PhotoStream 对象为for_classmates

我尝试childhood_photos.update(which_stream.add(for_classmates)),但它给了我一个错误:global name 'which_stream' is not defined

我该如何做这个操作?

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。看起来,这是 创建 新字段,但仅在 through 表中。在我看来,这也是我尝试的 update 过程所做的。因此它们是等价的。想确认我的想法是正确的,是吗?
    • “仅在直通表中”是什么意思?直通表是ManyToManyField 真正发生任何事情的唯一地方!这不是创建新字段(!?),而是将 for_classmates 流添加到所有所需的照片。
    • 使用update 操作仅更新该特定模型上的字段。 M2M 字段的问题在于,它们实际上并不是在特定表中创建的,而是在与您的第一个和第二个表相关的数据库中创建了一个新的直通表。所以在Photo 模型中做update 更新流与在通过表中创建行不同。
    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多