Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in Flask / SqlAlchemy

I have a class structure that looks similar to the below. The table that sqlalchemy creates with db.create_all looks good. Jobs are added with the appropriate columns filled out (school_id for Teachers, precinct_id for Policemen). My problem comes when trying to call do_stuff():

p = Teacher(...)
p.do_stuff()

returns "hey im the parent", which is the return value of Job. So even though everything is being inserted into the DB properly, it seems like the actual inheritance is not occurring but rather the only Model that is in place is a Job model. Is there a way to fix this or should I set this up in another way?

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'
like image 707
user592419 Avatar asked Aug 17 '26 05:08

user592419


1 Answers

I believe you need to specify the relationships between the models by using back-referencing or db.relationship(). These answers already offer a few options: backref & db.relationship and foreign key relationships

like image 170
kip2 Avatar answered Aug 18 '26 19:08

kip2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!