SQLAlchemy,各种表的外键引用

2024-09-30 14:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将外键引用id到多个表中

class HistoryActivation(Base):

    __tablename__ = 'active_control'

    id = Column(Integer, primary_key=True)
    id_entity = Column(Integer) #This one refer to any entity (id) that has a relation with this class.
    date = Column(DATE)
    user = Column(String(120))
    active = Column(BOOLEAN)

class Person(Base):

    __tablename__ = 'persons'

    id = Column(Integer, primary_key=True) 
    name = Column(String(50))

    history_activation = relationship("HistoryActivation",
            primaryjoin="HistoryActivation.id_entidade == Person.id")

class Company(Base):

    __tablename__ = 'companies'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))

    history_activation = relationship("HistoryActivation",
            primaryjoin="HistoryActivation.id_entidade == Company.id")


class Whatever(Base): ...

因此,id\u实体将id引用到各个表中,例如:

    id_entity = Column(Integer, ForeignKey('Person.id or Company.id or Whatever.id').

可以告诉ForeignKey可以引用多个关系吗


Tags: keyidtruebasestringcolumnintegercompany