Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM PostgreSQL DELETE query

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?

like image 230
Serhii Kushchenko Avatar asked Apr 06 '26 23:04

Serhii Kushchenko


1 Answers

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.

like image 123
DarK_FirefoX Avatar answered Apr 10 '26 02:04

DarK_FirefoX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!