David
David

Reputation: 120

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";

Upvotes: 9

Views: 8883

Answers (2)

bcattle
bcattle

Reputation: 12819

If you're using Postgresql, you can use a raw query with the USING clause

name_to_delete = 'Joe'
query = Message.raw("""
    DELETE FROM message 
        USING user 
    WHERE 
        message.from_user_id = user.id AND
        user.name = %s
""", name_to_delete)
query.execute()

Upvotes: 1

coleifer
coleifer

Reputation: 26245

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)
Message.delete().where(Message.user.in_(banned_users)).execute()

Upvotes: 13

Related Questions