如何使用 SQLAlchemy 核心进行自动连接?
Posted
技术标签:
【中文标题】如何使用 SQLAlchemy 核心进行自动连接?【英文标题】:How to do an automatic join using SQLAlchemy core? 【发布时间】:2021-02-10 22:29:39 【问题描述】:我在代表我的数据库的 sqlalchemy 中有以下 ORM 架构,我希望自动加入来自客户的发票。
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, ForeignKey, Integer, String
Base = declarative_base()
class Customer(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key=True)
name = Column(String)
address = Column(String)
email = Column(String)
invoices = relationship("Invoice", primaryjoin="Customer.id == Invoice.custid")
class Invoice(Base):
__tablename__ = 'invoices'
id = Column(Integer, primary_key=True)
custid = Column(Integer, ForeignKey("customers.id"))
invno = Column(Integer)
amount = Column(Integer)
如果我使用这种说法:
s = session.query(Customer, Invoice).join(Customer.invoices)
它给了我正确的结果:
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email, invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM customers JOIN invoices ON customers.id = invoices.custid
但是我想使用 SQL Alchemy 的核心,使用 Select、Join,没有查询,我该怎么做呢?
我试过了:
j = Customer.join(Customer.invoices)
stmt = select([Customer,Invoice]).select_from(j)
但不工作,有什么想法吗?
提前致谢。
【问题讨论】:
【参考方案1】:结果是:
s = select([Customer, Invoice]).select_from(join(Customer, Invoice))
【讨论】:
以上是关于如何使用 SQLAlchemy 核心进行自动连接?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 mysqlconnector 获取 sqlalchemy.create_engine 以使用 mysql_native_password 进行连接?