简体   繁体   English

使用Peewee中的连接删除表中的多个记录?

[英]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? 由于Peewee中的“删除”查询不允许加入,删除table_2中与相关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 如果您正在使用Postgresql,则可以使用带有USING子句的原始查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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