2012-04-23 3 views
2

모델 Thing 및 모델 Action이 있습니다. ThingAction 사이에는 일대 다 관계가 있습니다. 그러나 Action (예 : BuildAction, HealActionBloodyStupidAction)을 서브 클래스화할 수 있기를 바랍니다. Flask-SQLAlchemy를 사용하여이를 수행하고 단일 일대 다 관계를 유지할 수 있습니까?복수 모델과 일대 다 관계

답변

2

이 문제는 Inheritance Configuration 아래의 SQLAlchemy 문서에 설명되어 있습니다. 다른 하위 클래스가 동일한 데이터베이스 테이블을 공유하는 경우 single table inheritance을 사용해야합니다.

코드 예제 :

class Thing(db.Model): 
    __tablename__ = 'thing' 
    id = db.Column(db.Integer, primary_key=True) 
    actions = db.relationship('Action', backref=db.backref('thing')) 

class Action(db.Model): 
    __tablename__ = 'action' 
    id = db.Column(db.Integer, primary_key=True) 
    thing_id = db.Column(db.Integer, db.ForeignKey('thing.id')) 
    discriminator = db.Column('type', db.String(50)) 
    __mapper_args__ = {'polymorphic_on': discriminator} 

class BuildAction(Action): 
    __mapper_args__ = {'polymorphic_identity': 'build_action'} 
    time_required = db.Column(db.Integer) 

Action의 각 하위 클래스는 상위 클래스에 정의 된 thing 관계를 상속한다. action.type 열은 테이블의 각 행이 나타내는 하위 작업을 설명합니다.