![](/img/trans.png)
[英]How do I get a raw, compiled SQL query from a SQLAlchemy expression?
[英]How can I make property comparison able to be compiled to SQL expression in SQLAlchemy?
有两个表,表A的一列指向另一个表B的主键。
但是它们被放在不同的数据库中,所以我无法用外键配置它们。
通过relationship()
配置不可用,因此我手动实现了属性属性。
class User(Base):
__tablename__ = 'users'
id = Column(BigInteger, id_seq, primary=True)
name = Column(Unicode(256))
class Article(Base):
__tablename__ = 'articles'
__bind_key__ = 'another_engine'
# I am using custom session configures bind
# each mappers to multiple database engines via this attribute.
id = Column(BigInteger, id_seq, primary=True)
author_id = Column(BigInteger, nullable=False, index=True)
body = Column(UnicodeText, nullable=False)
@property
def author(self):
_session = object_session(self)
return _session.query(User).get(self.author_id)
@author.setter
def author(self, user):
if not isinstance(user, User):
raise TypeError('user must be a instance of User')
self.author_id = user.id
此代码适用于简单操作。 但它导致脏查询使SQLAlchemy的功能毫无意义。
如果通过relationship()
配置代码(例如query.filter(author=me)
)搞砸了(例如query.filter(author_id=me.id)
),代码就会很简单。
关系(例如,连接)相关的功能永远不能用于查询构建。
我是否可以在构建查询条件( filter()/filter_by()
)时使用属性属性?
你仍然可以在这里使用关系。 如果您坚持“延迟加载”,它将在数据库A中加载前导项后查询数据库B中的相关项。您可以在列中放置一个ForeignKey()指令,即使没有真正的指令也是如此。数据库。 或者您可以直接使用primaryjoin:
class User(Base):
__tablename__ = 'users'
id = Column(BigInteger, id_seq, primary=True)
name = Column(Unicode(256))
class Article(Base):
__tablename__ = 'articles'
__bind_key__ = 'another_engine'
id = Column(BigInteger, id_seq, primary=True)
author_id = Column(BigInteger, nullable=False, index=True)
body = Column(UnicodeText, nullable=False)
author = relationship("User",
primaryjoin="foreign(Article.author_id) == User.id")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.