我有一个关于 sqlalchemy 和数据库规范化的问题。
我有一个名为 Accounts 的表,以及 2 种人,Natural_Persons 和 Legal_Persons。
我一次只需要将一个帐户关联到一个人。
例如账号ID 4对应自然人ID 5。
但是... 我查询该信息时如何知道账户记录中的 ID 5 是来自自然人还是法人?
最简单的解决方案(目前对我而言)是在名为 person_type 的 Accounts 表中添加一个新字段,并使用例如 char 来区分它们。
所以现在我在帐户表中有一条记录,其中包含以下数据:
account_id = 4
person_id = 5
person_type = N
但现在我想将数据库与 sqlalchemy 一起使用。
如果我使用 Account 类实例加载账户记录,那么如果我访问“person”属性,它应该检查 person_type 字段并根据情况创建 NaturalPerson 类或 LegalPerson 类的实例!
类似于:
acc = Account(4)
acc.person
"""
if person_type == "L", person returns a LegalPerson instance
but otherwise ...
"""
最佳答案
Table inheritance是你要找的:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine, Column, Integer, ForeignKey, String
Base = declarative_base()
class Account(Base):
__tablename__ = 'account'
id = Column(Integer, primary_key=True)
person_id = Column(Integer, ForeignKey('person.id'))
person = relationship("Person")
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(20))
__mapper_args__ = {
'polymorphic_on':type,
'polymorphic_identity':'base'
}
class NaturalPerson(Person):
__mapper_args__ = {
'polymorphic_identity':'natural'
}
class LegalPerson(Person):
__mapper_args__ = {
'polymorphic_identity':'legal'
}
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
a = Account()
np = NaturalPerson()
a.person = np
session.add(a)
a = session.query(Account).first()
print type(a.person)
关于python - SQLAlchemy 和规范化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18492894/