简体   繁体   中英

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

You should use subqueries for this type of thing, eg:

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM