Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 463
David Avatar asked Oct 22 '15 20:10

David


2 Answers

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()
like image 119
coleifer Avatar answered Oct 13 '22 06:10

coleifer


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()
like image 34
bcattle Avatar answered Oct 13 '22 07:10

bcattle