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'>'
答案 0 :(得分:0)
问题是Mapper
不会将DeploymentJob
计为Job
的子项,直到Job
的映射器对象提供给DeploymentJob
的映射器对象为{{1}参数。所以这有效:
inherit