Search code examples
pythonpython-3.xsqlalchemypyramid

What is missing in the TaggedBlogRecord model for inheritance in sqlalchemy for it to work?


I am trying modify the pyramid_blogr example. The only closest QA thread is this one and the link mentioned in that thread. I went through both of them. I am using concrete inheritance, by which I understand that separate tables will be created for each model. Still, when I query records from the second model, I get errors saying that the model do have columns like title or created in TaggedBlogRecord.

Errors

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: ====> entries.created  <======
[SQL: SELECT entrieslanguage.id AS entrieslanguage_id 
FROM entrieslanguage ORDER BY entries.created DESC
 LIMIT ? OFFSET ?]

The sample code as follows

class BlogRecord(Base):
    __tablename__ = 'entries'
    id = Column(Integer, primary_key=True)
    title = Column(Unicode(255), unique=True, nullable=False)
    body = Column(UnicodeText, default=u'')
    created = Column(DateTime, default=datetime.datetime.utcnow)
    edited = Column(DateTime, default=datetime.datetime.utcnow)


class TaggedBlogRecord(BlogRecord):
    __tablename__ = 'taggedentries'
    __mapper_args__ = {'concrete':True}
    id = Column(Integer, primary_key=True)
    tags = Column(Unicode(255))

Solution

  • Read https://docs.sqlalchemy.org/en/latest/orm/inheritance.html#concrete-table-inheritance more closely (emphasis added):

    Two critical points should be noted:

    We must define all columns explicitly on each subclass, even those of the same name. A column such as Employee.name here is not copied out to the tables mapped by Manager or Engineer for us.

    while the Engineer and Manager classes are mapped in an inheritance relationship with Employee, they still do not include polymorphic loading. Meaning, if we query for Employee objects, the manager and engineer tables are not queried at all.