创建Django QuerySet快照的最有效方法是什么?

3

我是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()

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

1个回答

2
要保存查询集的“快照”,您可以获取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对象。 - Hannah Balenda
哦,我认为只需要 current_object_ids = list(Thing.objects.filter(source=importer).values_list('id', flat=True)) 就可以了吧? - Hannah Balenda
1
啊,是的,您需要将其转换为列表才能评估查询集。有关更多信息,请参见此处:https://dev59.com/qYTba4cB1Zd3GeqP1BQk#26254561 - coler-j

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接