我有一套现有的sqlalchemy模型,如此
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String)
first_name = Column(String)
last_name = Column(String)
email = Column(String)
user_group = Table('user_group', Base.metadata,
Column('user_id', Integer, ForeignKey('users.id')),
Column('group_id', Integer, ForeignKey('groups.id'))
)
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship("User", secondary=user_group)
我希望创建第三个模型,该模型与User
或Group
类型具有1对多的关系。所以我想最终得到像这样可以使用的东西
class Contact(Base):
__tablename__ = 'contacts'
id = Column(Integer, primary_key=True)
type_id = Column(Integer) # the id of the group or user row which it refers to.
type = Column(String) # 'group' or 'user'
class Thing(Base):
__tablename__ = 'things'
relationship('Contact') # Array of Contacts
,其中
thing = Thing()
thing.contacts[0].type # returns 'group' or 'user'
thing.contacts[0].contact # returns the actual User or Group object
我知道这可以通过继承来完成,但还有其他选择吗?我不必将我的基本用户和组模型子类化。
提前致谢!