7

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'
4
  • I couldn't replicate your problem, but perhaps its worth looking into inheritance in sqlalchemy: docs.sqlalchemy.org/en/rel_0_8/orm/… Commented Jun 13, 2013 at 8:40
  • Using the code you show, the code should work. Please verify how much your actual code is different from the sample you put here. Commented Jun 13, 2013 at 12:18
  • As your problem is anything responding as a "Job", I think you use single table inheritance and you miss a "type" column as stated in SQLA doc. Those SQLA always fetch a Job, even if you can fullfill the school_id/precinct_id fileds which are present in table. Your code is not complete and you should the __mapper_args__ and __tablename__ you use. Commented Jun 14, 2013 at 10:15
  • I didn't actually fill in those. I let those be filled in automatically. I ended up scrapping this model and working off of a different, simpler one. I lose the advantages of Polymorphism but gained some simplicity where it was probably more important. Commented Jun 18, 2013 at 0:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.