在 SQL Alchemy 中,我在数据库中定义了相当多的表。奇怪的是,每次我想访问该数据库上的元素时,我都必须导入文件中的元素。感觉不对(我有 Perl 背景,导入是在表文件中延迟完成的)。我尝试使用基表定义添加要导入到文件中的内容,但这显然会导致循环循环并且无法启动。我缺少什么吗?我将提供一个基本示例,说明表定义的外观以及如何访问下面的对象。 (我没有创建数据库,我只是创建一个新系统来访问它)
地址类别:
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship, backref
from my_app.db.product import Base
class Address(Base):
__tablename__ = 'Addresses'
AddressId = Column(Integer, primary_key=True)
ClientId = Column(Integer, ForeignKey('Clients.ClientId'))
CountryId = Column(Integer, ForeignKey('Countries.CountryId'))
AddressLine1 = Column(String)
AddressLine2 = Column(String)
Town = Column(String)
County = Column(String)
PostCode = Column(String)
BusinessName = Column(String)
Client = relationship("Client", backref=backref("Addresses"))
Country = relationship("Country", backref=backref("Addresses"))
def __init__(self, AddressLine1, AddressLine2, Town, County, PostCode, ClientId,
BusinessName, CountryId):
self.AddressLine1 = AddressLine1
self.AddressLine2 = AddressLine2
self.Town = Town
self.County = County
self.PostCode = PostCode
self.ClientId = ClientId
self.BusinessName = BusinessName
self.IsDeleted = IsDeleted
self.CountryId = CountryId
self.IsInvoiceAddress = IsInvoiceAddress
客户端类:
from sqlalchemy import Column, String, Integer, DateTime, Double, ForeignKey
from my_app.db.product import Base
class Client(Base):
__tablename__ = 'Clients'
ClientId = Column(Integer, primary_key=True)
Name = Column(String)
AccountNo = Column(String)
Email = Column(String)
DateCreated = Column(DateTime)
def __init__(self, Name, AccountNo, Email, DateCreated):
self.Name = Name
self.AccountNo = AccountNo
self.Email = Email
self.DateCreated = DateCreated
访问类似(为简单起见,进行了精简):
from my_app.db.product.address import Address
from my_app.db.product.client import Client
address_rs= session.query(Address).all()
for address in address_rs:
client = address.Client
上面的代码可以工作,但我对导入 Client 对象和 Address 对象并不满意 - 当我在模块中有很多连接时,它会变得笨拙。
有什么我可以尝试测试并希望解决这个问题的吗?我不确定这是否是错误的,但是来自 Perl DBIx::Class 背景后感觉不对。
SQLAlchemy 需要导入所有继承自
Base
的模型类,才能形成 SQL 查询。由于引用和反向引用,在使用任何模型类之前需要解决这些问题,这是 SQLAlchemy 通常在幕后执行的一步。
虽然它可能适用于简单的用例,但不太可能带来您想要的好处。
不过,你可以做到。您仍然可以动态导入和初始化
Base
例如使用 DeferredReflection
机制的以下代码:
基础.py:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeferredReflection
Base = declarative_base()
class DynamicBase(DeferredReflection, Base):
"""Create a model that is dynamically initialised."""
class MyModel(DynamicBase):
pass
然后就可以初始化SQLAlchemy了
from sqlalchemy.ext.declarative import DeferredReflection
# At this point you need have imported all Python modules that inherit from Base
DeferredReflection.prepare(engine)
然而,这样做的任何“导入速度”好处通常都不值得头痛。