0

I want to execute an SQL query, when an item gets deleted in the admin interface. In models.py I do this:

from django.db import connection

class LList(models.Model):
    item = models.ForeignKey(Item, models.DO_NOTHING)

    def delete(self, *args, **kwargs):
        cursor = connection.cursor()
        cursor.execute('DELETE FROM some_table where item = %d', [self.item.id])

When I turn debugging on I see all the queries executed. It seems the DELETE FROM query is not executed, I only see

(0.000) DELETE FROM `llist` WHERE `llist`.`id` IN (27); args=(27,)

Why is the other DELETE FROM query not executed? How can I fix that?

2
  • How did you execute the delete operation in the admin interface? Commented Oct 9, 2019 at 6:04
  • Oh I see what you mean, didn't know there were 2 possibilities to delete an item. I want the SQL query beeing executed in both possible ways, with delete selected and delete. Commented Oct 9, 2019 at 15:27

1 Answer 1

2

You are overriding the delete function the wrong way,

def delete(self, using=None, keep_parents=False):
    with connection.cursor() as cursor:
        cursor.execute('''DELETE FROM some_table where item = %d''', [self.item.id])

    super(LList, self).delete(using, keep_parents)

But I believe the better way would be to do it using signals, you should create a pre_delete signal.

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

2 Comments

Great, this way the direct delete works, but when I delete the item via delete selected it does not work. What kind of function do I have to call in this case?
Can you please write down the sql query that you are trying to execute. I will be better able to solve the problem then.

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.