【问题标题】:SQLAlchemy and NormalizationSQLAlchemy 和规范化
【发布时间】:2013-08-31 19:42:47
【问题描述】:

我有一个关于 sqlalchemy 和 DB 规范化的问题。

我有一个名为 Accounts 的表,以及 2 种人,Natural_Persons 和 Legal_Persons。

我一次只需要将一个帐户与一个人关联。

例如,帐户 ID 4 与 Natural_Person ID 5 相关。

但是...当我查询该信息时,我如何知道帐户记录中的 ID 5 是来自自然人还是法人?

最简单的解决方案(目前对我而言)是在 Accounts 表中添加一个名为 person_type 的新字段,并使用例如字符来区分它们。

所以现在我在帐户表中有一条记录,其中包含以下数据:

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 ...
"""

【问题讨论】:

  • 这能回答你的问题吗? How can you represent inheritance in a database?
  • 请在考虑发布之前阅读您的教科书和/或手册和谷歌任何错误消息或您的问题/问题/目标的许多清晰、简洁和精确的措辞,有或没有您的特定字符串/名称和站点:stackoverflow.com & 标签;阅读许多答案。如果您发布问题,请使用一个短语作为标题。反映你的研究。请参阅How to Ask 和投票箭头鼠标悬停文本。 PS 这个问题的重排不是归一化的。

标签: python mysql database sqlalchemy database-normalization


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2012-05-22
    • 2013-08-11
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    相关资源
    最近更新 更多