【问题标题】:Most efficient way to create a snapshot of a django queryset?创建 django 查询集快照的最有效方法?
【发布时间】:2019-08-25 13:45:49
【问题描述】:

我是 Django 新手,我需要在导入器重新运行之前清理所有符合特定条件的现有对象,这些条件之前由导入器创建。

我正在尝试找出最有效的方法来做到这一点。目前,我在导入新对象并使用布尔值 to_be_deleted=True 更新它们之前获取现有对象:

Thing.objects.filter(source=importer).update(to_be_deleted=True)
import_new_things(source=importer)
Thing.objects.filter(to_be_deleted=True).delete()

但是我真的需要在整个查询集上运行更新吗?有没有办法将查询集的快照保存到变量中,然后在导入器完成后删除它们?

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    要保存查询集的“快照”,您只需获取 ID 列表即可。

    # Get all the objects IDs
    current_object_ids = list(Thing.objects.filter(source=importer).values_list('id', flat=True))
    

    然后你可以调用你的函数,如果它成功了你可以删除你的其他对象。

    try:
        import_new_things(source=importer)
    except: 
        # do something
    else:
        # Run your delete
        Thing.objects.filter(id__in=current_object_ids).delete()
    

    【讨论】:

    • 不确定我错过了什么,但是当我尝试这个建议时,Thing.objects.filter(id__in=current_object_ids) 返回每​​个 Thing 对象。
    • 哦,我想只要是current_object_ids = list(Thing.objects.filter(source=importer).values_list('id', flat=True))?
    • 啊,是的,您需要将其转换为列表才能评估查询集。请参阅此处了解更多信息:stackoverflow.com/a/26254561/1689262
    猜你喜欢
    • 2012-10-08
    • 2012-02-21
    • 2012-10-14
    • 2023-01-07
    • 2011-04-25
    • 2016-10-04
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多