Deleting multiple records in a table using join in Peewee?
Asked Answered
E

2

9

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";
Endure answered 22/10, 2015 at 20:40 Comment(0)
C
13

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()
Chalco answered 24/10, 2015 at 5:47 Comment(3)
This works but I believe the question is how to do a: delete a from a,b where a.field1=b.field2 where ... type of queryMatless
Thank you Coleifer. But indeed, I'm wondering if there's a way to avoid using subqueries?Endure
From lack of reply, I'll suppose this is not possible. :-)Endure
B
1

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()
Blancmange answered 28/6, 2016 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.