【发布时间】:2012-03-15 20:30:17
【问题描述】:
我需要一些帮助来理解 SQLAlchemy 中的继承是如何工作的。我为具有一些基本功能的用户创建了一个基类。然后是一些特定的用户(admin、cooluser、uncooluser)。每个都有独特的功能,所以我决定在 SQLAlchemy 中使用继承。问题是我需要能够随时将用户升级为cooluser或uncooluser,并将cooluser降级为用户。
class User(Base):
__tablename__ = 'tbl_users'
__table_args__ = {'mysql_engine': 'InnoDB'}
user_id = Column(Integer, primary_key = True, unique = True, nullable = False)
user_name = Column(String(100), nullable = False, unique = True)
password = Column(String(100), nullable = False)
user_type = Column('user_type', String(50))
first_name = Column(String(50), nullable = False)
last_name = Column(String(50), nullable = False)
address = Column(String(50), nullable = False)
city = Column(String(20), nullable = False)
postal_code = Column(String(10), nullable = False)
country_id = Column(Integer, ForeignKey(Contries.country_id))
country = relationship('Country', backref = 'users')
query = Session.query_property()
__mapper_args__ = {'polymorphic_on': user_type, 'polymorphic_identity': 'User'}
class CoolUser(User):
__tablename__ = 'tbl_cool_user'
__table_args__ = {'mysql_engine': 'InnoDB'}
__mapper_args__ = {'polymorphic_identity': 'CoolUser'}
cool_user_id = Column(Integer, ForeignKey(User.user_id, ondelete = 'CASCADE'), primary_key = True)
cool_user_balance = Column(Numeric(15, 3))
我可以创建 CoolUser 而不在 'tbl_users' 中创建新行,而是使用现有行吗?可以更改一些设置,以便当 CoolUser 被删除时,它只删除“tbl_cool_user”中的条目,而不是“tbl_user”?
我错过了 SQLAlchemy 中的继承点吗?
【问题讨论】:
标签: python inheritance sqlalchemy