简体   繁体   English

加入Peewee的查询

[英]Join Queries in Peewee

Hello Stackoverflow Community, 您好Stackoverflow社区,

I have just started working on peewee application and little stuck with join queries. 我刚刚开始研究peewee应用程序,对连接查询几乎一无所知。 Currently, I have following models setup : 目前,我有以下模型设置:

class Equipment(BaseModel):
    equip_id = CharField(primary_key=True)
    is_fullset = BooleanField(default=False)


class Department(BaseModel):
    dept_id = IntegerField(primary_key=True)
    dept_name = CharField()


class User(BaseModel):
    email = CharField(primary_key=True)
    equip_id_fk = ForeignKeyField(Equipment, related_name="equipments", null=True)
    dept_id_fk = ForeignKeyField(Department, related_name="departments")
    user_name = CharField()

I want to display a view/table that will hold combined information of all the table. 我想显示一个视图/表,其中将包含所有表的组合信息。 I tried doing this like this for User and Equipment (for now) : 我尝试对用户和设备这样做(现在):

  query = (Equipment.select(Equipment, User).join(User, JOIN.LEFT_OUTER))

Here I get equipment values first and then User. 在这里,我先获取设备值,然后再获取用户。 I tried changing User with Equipment and vice versa, but didn't work out well. 我尝试使用设备更改用户,反之亦然,但效果不佳。 Basically, I want to display all these three tables into one singular table in this order: 基本上,我想按以下顺序将所有这三个表显示为一个单表:

User Name || User Email || Dept_ID || Dept_NAME || EQUIP_ID || Is_Fullset

Please let me know if I need to change my models or query. 如果需要更改型号或查询,请告诉我。 Any help would be really appreciated. 任何帮助将非常感激。

query = (User
         .select(User, Equipment, Department)
         .join(Equipment, JOIN.INNER)
         .switch(User)
         .join(Department, JOIN.INNER))
for row in query:
    print(row.user_name, row.email, row.dept_id_fk.dept_id,
          row.dept_id_fk.dept_name, row.equip_id_fk.equip_id,
          row.equip_id_fk.is_fullset)

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

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