【问题标题】:Peewee join query can't get dataPeewee 连接查询无法获取数据
【发布时间】:2021-03-24 18:31:38
【问题描述】:

我的数据库中有以下 2 个表。

tbl_customers
cid (int auto)
name (text)

tbl_contacts
cid
email
name
phone

我正在尝试在 peewee 中编写以下 sql 查询,但无法正常工作

SELECT tbl_customers.cid, tbl_contacts.name
FROM tbl_customers
INNER JOIN tbl_contacts ON tbl_customers.cid = tbl_contacts.cid
WHERE tbl_customers.cid = '5';

我正在尝试让数据像这样显示

tbl_customer.cid = 5
tbl_contacts.name = 'Test User'

根据我发现的谷歌搜索,我在 peewee 中尝试了以下操作。

tbl_customers.select(tbl_customers.cid, tbl_contacts.name).join(tbl_contacts, on=(tbl_customers.cid == tbl_contacts.cid)).where(tbl_customers.cid == '5')

【问题讨论】:

    标签: peewee


    【解决方案1】:

    Peewee 会自动将您的模型放入图表中,因此可以访问联系人姓名,如下所示:

    customer.contact.name
    

    如果您只想要单个模型实例上的所有数据,您可以将“.objects()”附加到您的查询中,它会将所有列数据放在正在选择的实例类型上。

    这已被彻底记录:

    http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources

    【讨论】:

    • 感谢您的回复,但是有些事情没有意义,当我打印出 peewee 正在执行的查询时,我采用相同的确切查询并将其放入 sqlite3 它给出了正确的数据回来。但由于某些原因,peewee 不确定为什么
    • 如果你阅读了我的评论和链接的文件,希望这能澄清事情......
    猜你喜欢
    • 2019-08-23
    • 2021-04-22
    • 1970-01-01
    • 2023-03-13
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多