簡體   English   中英

如何在SQLAlchemy中將屬性比較編譯為SQL表達式?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM