2013-08-28 166 views
0

我有一個關於SQLAlchemy的和DB正常化問題...SQLAlchemy的和規範化

我有一個表叫帳戶,和2種人...... Natural_Persons和Legal_Persons的...

的一點是我需要一個帳戶,涉及到在同一時間只有一個人......

例如,帳戶ID 4與Natural_Person ID 5相關...

但是....我怎麼可以知道當我查詢該信息時,如果賬戶記錄中的ID 5來自Na王興仁人或一個法律問題....

(目前對我來說)最簡單的解決方案,即將一個新字段添加到帳戶表...叫person_type,並使用例如,一個char以區分他們..

所以現在,即我在帳戶表中有一個記錄與以下數據。

account_id = 4 
person_id = 5 
person_type = N 

但是......現在......我想工作的分貝與SQLAlchemy的

如果我使用賬戶類實例加載帳戶記錄..然後,如果我進入了「人」的屬性它應檢查person_type字段並創建NaturalPerson類或LegalPerson類的實例!

喜歡的東西:

acc = Account(4) 
acc.person 

""" 
if person_type == "L", person returns a LegalPerson instance.... but otherwise. 
""" 

希望你能幫幫我!請!

回答

0

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)