我对sqlalchemy下的继承感到有点困惑,我甚至不确定我应该在这里使用什么类型的继承(单表,连接表,具体).我有一个基类,其中包含一些在子类之间共享的信息,以及一些完全独立的数据.有时候,我会想要来自所有类的数据,有时只需要来自子类的数据.这是一个例子:
class Building:
def __init__(self, x, y):
self.x = x
self.y = y
class Commercial(Building):
def __init__(self, x, y, business):
Building.__init__(self, x, y)
self.business = business
class Residential(Building):
def __init__(self, x, y, numResidents):
Building.__init__(self, x, y, layer)
self.numResidents = numResidents
Run Code Online (Sandbox Code Playgroud)
我如何使用声明式将其转换为SQLAlchemy?那么,如何将我查询该建筑物内x>5和y>3?或者哪些住宅楼只有1个居民?
我有一个类似于下面的类结构.sqlalchemy使用db.create_all创建的表看起来不错.添加了相应列的作业(教师的school_id,警察的precinct_id).尝试调用do_stuff()时出现问题:
p = Teacher(...)
p.do_stuff()
Run Code Online (Sandbox Code Playgroud)
返回"hey im the parent",这是Job的返回值.因此,即使所有内容都正确地插入到数据库中,看起来实际的继承似乎没有发生,而是唯一的模型就是作业模型.有没有办法解决这个问题,还是应该以另一种方式设置?
class Job(db.Model):
id = Column(Integer, primary_key=True)
...
def __init__(...):
...
def do_stuff(self):
print 'hey im the parent'
class Teacher(Job):
school_id = Column(Integer, ForeignKey('school.id'))
def __init__(...):
super(Teacher, self).__init__(...)
self.school_id = school_id
def do_stuff(self):
print 'teacher here'
class Policeman(Job):
precinct_id = Column(Integer, ForeignKey'precinct.id'))
def __init__(...):
super(Policeman, self).__init__(...)
self.precinct_id = precinct_id
def do_stuff(self):
print 'police ack'
Run Code Online (Sandbox Code Playgroud)