django orm postgresql删除查询

发布于 2025-02-05 08:14:09 字数 501 浏览 1 评论 0原文

我有30个实例的对象,即数据库表中的30行。

在Python代码中,我有room.objects.all()。delete()

我看到django orm将其转换为以下postgresql查询:从“ app_name_room”中删除where“ app_name_room”。“ ID”($ 1,$ 1,$ 2,$ 2,$ 3,$ 4,$ 5,$ 5,$ 6,$ 6,$ 7,$ 8,$ 8,$ 8,$ 9,$ 9,$ 10,$ 10,$ 10,$ 10,$ 10 ,$ 11,$ 12,$ 13,$ 14,$ 15,$ 16,$ 17,$ 18,$ 19,$ 20,$ 20,$ 21,$ 22,$ 22,$ 23,$ 24,25,$ 25,26,$ 27,$ 27,$ 28,$ 29,$ 29,$ 30)

为什么django orm不使用app_name_room 查询更简单的删除?有什么方法可以切换到它并避免列出所有ID?

I have 30 instances of the Room objects, i.e. 30 rows in the database table.

In Python code I have Room.objects.all().delete().

I see that Django ORM translated it into the following PostgreSQL query: DELETE FROM "app_name_room" WHERE "app_name_room"."id" IN ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30).

Why doesn't the Django ORM use a more parsimonious DELETE FROM app_name_room query? Is there any way to switch to it and avoid listing all IDs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吲‖鸣 2025-02-12 08:14:09

有趣的问题。这让我想到了,所以我走了更深入。主要原因可能是使用app_name_room delete 删除cascacade delete

,但是回答您的问题

有什么方法可以切换到它并避免列出所有ID?

您可以使用私有方法_RAW_DELETE进行此操作。例如:

objects_to_delete = Foo.objects.all()
objects_to_delete._raw_delete(objects_to_delete.db)

这将执行以下查询:

DELETE FROM "objects_to_delete"

PS:根据功能docstring

从单个直接SQL查询中从给定的QuerySet中找到的对象。没有发送信号,也没有对级联的保护。

Interesting question. It got me thinking so I went a little deeper. The main reason could be that using DELETE FROM app_name_room doesn't take care of CASCADE delete

However, answering your question

Is there any way to switch to it and avoid listing all IDs?

You can do this using the private method _raw_delete. For instance:

objects_to_delete = Foo.objects.all()
objects_to_delete._raw_delete(objects_to_delete.db)

This will execute the following query:

DELETE FROM "objects_to_delete"

PS: According to the function docstring:

Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文