如何将通用的“Contact”附加到多个不同的表?

How can I attach generic `Contact` to multiple different tables?

我正在尝试创建一组表,这些表都可以 Contact 分配给它们。

class Contact(Base):
    __tablename__ = "contact"
    id = Column(Integer, primary_key=True)
    name = Column(String, index=True, nullable=False, doc="Name of the contact.")
    phone = Column(String, index=True, doc="Phone number of the contact.")

可以从其他各种表链接到联系人,一条记录可以在不同领域有多个联系人。

class BusinessGroup(Base):
    __tablename__ = "business_group"
    id = Column(Integer, primary_key=True)
    name = Column(String, index=True, nullable=False, doc="Name of the group.")
    main_contact = Column(Integer, ForeignKey("contact.id"), doc="Main contact details for the group.")
    second_contact = Column(Integer, ForeignKey("contact.id"), doc="Second contact details for the group.")

class Vendor(Base):
    __tablename__ = "vendor"
    id = Column(Integer, primary_key=True)
    name = Column(String, index=True, nullable=False, doc="Name of the vendor.")
    contact = Column(Integer, ForeignKey("contact.id"), doc="Main contact details for the vendor.")

此设置似乎有效,但在 flask-admin 中,为 BusinessGroupVendor 创建新项目时没有显示联系人字段。

我怎样才能让这个设计发挥作用?或者我应该用完全不同的方式来模拟这种关系吗?

我最终对 Contact table 进行了子类化,这样我就可以:

class MainContact(Contact):
    __tablename__ = "main_contact"
    id = Column(Integer, ForeignKey("contact.id"), primary_key=True)
    business_group = relationship("BusinessGroup", back_populates="main_contact")
    business_group_id = Column(Integer, ForeignKey("business_group.id"), nullable=False)
    ...

class SecondContact(Contact):
    __tablename__ = "second_contact"
    id = Column(Integer, ForeignKey("contact.id"), primary_key=True)
    business_group = relationship("BusinessGroup", back_populates="second_contact")
    business_group_id = Column(Integer, ForeignKey("business_group.id"), nullable=False)
    ...

class BusinessGroup(Base):
    __tablename__ = "business_group"
    id = Column(Integer, primary_key=True)
    name = Column(String, index=True, nullable=False, doc="Name of the group.")
    main_contact = relationship(
        "MainContact", back_populates="business_group", uselist=False, 
        doc="Main contact details for the business_group."
    )
    second_contact = relationship(
        "SecondContact", back_populates="business_group", uselist=False, 
        doc="Second contact details for the business_group."
    )

除了需要子类化以便我们可以从同一模型中引用两个不同的联系人外,另一个重要部分是添加外键关系,以便联系人显示在 Flask 管理面板中。