SQLAlchemy,外键引用各种表

时间:2016-12-20 02:34:09

标签: python sqlalchemy

如何将外键引用到多个表的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_entity引用各种表的id,如:

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

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

0 个答案:

没有答案