簡體   English   中英

SQLAlchemy 聲明的屬性在具有外鍵的列上

[英]SQLAlchemy declared_attr on Column with Foreign Key

我有一個設置,我正在使用抽象機器基礎 class ,它有幾個用於不同類型機器的子類。 原因是我想為這些機器使用不同的數據庫模式,這些機器有一些相似但有些完全不同的表。

class Machine(Base):
    __abstract__ = True
    __tablename__ = 'machines'

    id = Column('id', BigInteger, nullable=False, primary_key=True)


class MachineA(Machine):
    system = relationship('SystemA')
   
    __table_args__ = {'schema': 'A'}


class MachineB(Machine):
    system = relationship('SystemB')
   
    __table_args__ = {'schema': 'B'}

到目前為止,這是按預期工作的,但是一旦我開始為各個模式添加帶有外鍵的表,我就會遇到問題。

以下是系統表的示例:

class System(Base):
    __tablename__ = 'system'
    __abstract__ = True

    id = Column('id', BigInteger, primary_key=True, autoincrement=True)
    machine_id = Column(BigInteger, ForeignKey('machines.id'), nullable=False)
    ts = Column('ts', TIMESTAMP(timezone=True), nullable=False)
    value = Column('value', JSONB())

    __table_args__ = (UniqueConstraint('machine_id', ts, value),
                      Index('system_machine_id_index', machine_id),
                      Index('system_ts_index', ts))


class SystemA(System):

    __table_args__ = (*System.__table_args__,
                      {'schema': 'A'})


class SystemB(System):

    __table_args__ = (*System.__table_args__,
                      {'schema': 'B'})

創建表時,會引發以下錯誤:

sqlalchemy.exc.InvalidRequestError: Columns with foreign keys to other columns must be declared as @declared_attr callables on declarative mixin classes.
  For dataclass field() objects, use a lambda:.

我嘗試使用:

@declared_attr
def machine_id(cls):
    return Column(BigInteger, ForeignKey('machines.id'), nullable=False)

這沒有用。 我錯過了什么嗎? 謝謝!

找到了解決方案。 我不得不將 machine_id 設為字符串:

__table_args__ = (UniqueConstraint('machine_id', ts, value),
                      Index('system_machine_id_index', 'machine_id'),
                      Index('system_ts_index', ts))

更重要的是,在 ForeignKey 調用中引用架構:

@declared_attr
def machine_id(cls):
    return Column(BigInteger, ForeignKey('A.machines.id'), nullable=False)

在 __table_args__ 中指定模式對於 mixin 聲明是不夠的。

你可以試試這個

@declarative_mixin class System(Base): ... @declared_attr def machine_id(cls): ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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