Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使属性比较能够在SQLAlchemy中编译为SQL表达式?_Python_Orm_Sqlalchemy - Fatal编程技术网

Python 如何使属性比较能够在SQLAlchemy中编译为SQL表达式?

Python 如何使属性比较能够在SQLAlchemy中编译为SQL表达式?,python,orm,sqlalchemy,Python,Orm,Sqlalchemy,有两个表,表A的一列指向另一个表B的主键 但它们被放在不同的数据库中,所以我不能用外键配置它们 无法通过relationship()进行配置,因此我手动实现了属性 class User(Base): __tablename__ = 'users' id = Column(BigInteger, id_seq, primary=True) name = Column(Unicode(256)) class Article(Base): __tablename__

有两个表,表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\u id=me.id)

与关系(如连接)相关的功能永远无法用于查询生成


我至少可以在构建查询条件(
filter()/filter\u by()
)时使用property属性吗?

您仍然可以在此处使用关系。如果您坚持“延迟加载”,则在加载数据库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")

哦,谢谢!无法使用join/joinedload,因为编译后的查询将在单个数据库引擎中执行,该引擎被映射为执行查询的主映射器。但是访问关系属性,在过滤表达式中使用它,工作起来令人惊讶!