4

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?

3
  • Do you have any ForeignKeys in other models pointing to your Room model or signal handlers that trigger for the Room model? Commented Jun 8, 2022 at 13:20
  • ForeignKeys in other models pointing to your Room model or signal handlers that trigger for the Room model - yes, both Commented Jun 8, 2022 at 13:30
  • 3
    Django has to retrieve all objects being deleted to cascade the delete to related objects and run the signal handlers, are you fine with skipping that because that's the only built-in way to do what you want at the moment Commented Jun 8, 2022 at 13:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.