简体   繁体   English

是否可以使用 peewee python ORM 在多个字段上进行 sql join?

[英]Is it possible to make sql join on several fields using peewee python ORM?

Assuming we have these three models.假设我们有这三个模型。

class Item(BaseModel):
    title = CharField()

class User(BaseModel):
    name = CharField()

class UserAnswer(BaseModel):
    user = ForeignKeyField(User, 'user_answers')
    item = ForeignKeyField(Item, 'user_answers_items')
    answer = ForeignKeyField(Item, 'user_answers')

I want to get all Items which does not have related UserAnswer records for current user.我想获取当前用户没有相关UserAnswer记录的所有Items In SQL it would be something like this:在 SQL 中,它会是这样的:

select * from item i
left join useranswer ua on ua.item_id=i.id and ua.user_id=1
where ua.id is null;

Is it possible to make a left outer join with constraint on two fields using peewee syntax?是否可以使用 peewee 语法对两个字段进行左外连接? It will be cool if I can do it in this way:如果我能这样做,那会很酷:

Item.select().join(UserAnswer, JOIN_LEFT_OUTER, on=['__my_constraints_here__']).where(
    (UserAnswer.id.is_null(True))
)

Yes you can join on multiple conditions:是的,您可以在多个条件下加入:

join_cond = (
    (UserAnswer.item == Item) &
    (UserAnswer.user == 1))
query = (Item
         .select()
         .join(
             UserAnswer,
             JOIN.LEFT_OUTER,
             on=join_cond))
         .where(UserAnswer.id.is_null(True)))

Docs here:http://docs.peewee-orm.com/en/latest/peewee/api.html#Query.join文档在这里:http ://docs.peewee-orm.com/en/latest/peewee/api.html#Query.join

Sorry there is not an example of using multiple join conditions, but the on is just an arbitrary expression so you can put any valid peewee "Expression" you like there.抱歉,没有使用多个连接条件的示例,但on只是一个任意表达式,因此您可以在其中放置任何您喜欢的有效 peewee“表达式”。

Important: you should import JOIN - from peewee import JOIN重要提示:您应该导入 JOIN - from peewee import JOIN

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

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