David David - 1 year ago 222
Python Question

Deleting multiple records in a table using join in Peewee?

Since joining is not allowed on "delete" queries in Peewee, what is the best way to delete all records in table_2 that match a specific condition in related table_1?

Using a simple example, I want to achieve the equivalent of this:

DELETE message.*
FROM message
JOIN user ON message.from_user_id = user.id
WHERE user.name = "Joe";

Answer Source

You should use subqueries for this type of thing, e.g.:

joe = User.select().where(User.username == 'Joe')
Message.delete().where(Message.from_user == joe).execute()

Let's say you want to delete all messages from "banned" users. You could write:

banned_users = User.select().where(User.is_banned == True)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download