在SQLAlchemy关系中放置子类的实例

时间:2016-07-13 14:05:41

标签: python sqlalchemy

TLDR ;问题出在继承构造中,我不知道如何在没有声明性API的情况下制作它。

我制作了一般模型Job,它将进一步缩小像DeploymentJob这样的子类。每个Job由多个Actions组成。如果我定义了这个Job<->Action关系,我就不能在Job子类实例中使用它。

from sqlalchemy import (Table, Binary, Column as C, String, Integer,
                        ForeignKey, create_engine, MetaData)
from sqlalchemy.orm import (mapper, relationship, backref, scoped_session,
                            sessionmaker)


metadata = MetaData()
db_engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(bind=db_engine))

class Job(object):
    pass

class DeploymentJob(Job):
    def __init__(self, *args, **kwargs):
        super(DeploymentJob, self).__init__(*args, **kwargs)

class Action(object):
    def __init__(self, unit, job):
        self.unit = unit
        self.job = job

jobs = Table('jobs', metadata,
             C('id', Integer, primary_key=True),
             C('type', String, nullable=False)
)

deployment_jobs = Table('deployment_jobs', metadata,
                        C('id', ForeignKey('jobs.id'), primary_key=True)
)

actions = Table('actions', metadata,
                C('job_id', ForeignKey('jobs.id'), primary_key=True),
                C('unit', String, primary_key=True)
)

mapper(Job,
       jobs,
       polymorphic_on=jobs.c.type,
       properties = {
           'actions': relationship(Action, lazy='dynamic', uselist=True,
                                   backref=backref('job', uselist=False)),
    }
)

mapper(DeploymentJob, deployment_jobs, polymorphic_identity='deployment')

mapper(Action, actions)


metadata.create_all(bind=db_engine)
unit = 'second-machine'
job = DeploymentJob()
action = Action(unit, job)

print "action.job -> %s is job: %s" % (action.job, isinstance(action.job, Job))
# >> action.job -> <__main__.DeploymentJob object at 0x7fe> is job: True

db_session.add(action)
db_session.add(job)

db_session.commit()

我希望DevelopmentJob被接受为Job个实例,但不会发生此关联:

AssertionError: Attribute 'job' on class '<class '__main__.Action'>' doesn't handle objects of type '<class '__main__.DeploymentJob'>'

1 个答案:

答案 0 :(得分:0)

问题是Mapper不会将DeploymentJob计为Job的子项,直到Job的映射器对象提供给DeploymentJob的映射器对象为{{1}参数。所以这有效:

inherit