Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7497593
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T19:09:15+00:00 2026-05-29T19:09:15+00:00

I am using the concrete table inheritance with SQLAlchemy. In declartive style model class,

  • 0

I am using the concrete table inheritance with SQLAlchemy. In declartive style model class, I have configured it successfully.

My code just like:

class Entry(AbstractConcreteBase, db.Model):
    """Base Class of Entry."""

    id = db.Column(db.Integer, primary_key=True, nullable=False)
    created = db.Column(db.DateTime, nullable=False)
    post_id = declared_attr(lambda c: db.Column(db.ForeignKey("post.id")))
    post = declared_attr(lambda c: db.relationship("Post", lazy="joined"))

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    @declared_attr
    def __mapper_args__(cls):
        # configurate subclasses about concrete table inheritance
        return {'polymorphic_identity': cls.__name__,
                'concrete': True} if cls.__name__ != "Entry" else {}

class TextEntry(Entry):
    """Text and Article Entry."""

    text = db.deferred(db.Column(db.Text, nullable=False))

class PhotoEntry(Entry):
    """Photo Entry."""

    path = db.deferred(db.Column(db.String(256), nullable=False))

It works fine while testing it in the shell:

>>> from models.entry import Entry
>>>
>>> Entry.query.all()
[<PhotoEntry 'Title' created by tonyseek>,
 <PhotoEntry 'TITLE 2' created by tonyseek>,
 <PhotoEntry 'Title 3' created by tonyseek>,
 <PhotoEntry 'Title 4' created by tonyseek>,
 <TextEntry 'Title' created by tonyseek>]

Then I fall into trouble while setting the relationship in other models. Each entry has a foreign key post_id to join Post model, but I could not define the back reference in Post. That can’t work:

class Post(db.Model):
    """An Post."""

    id = db.Column(db.Integer, primary_key=True, nullable=False)
    description = db.Column(db.Unicode(140), nullable=False)
    entries = db.relationship(Entry, lazy="dynamic")

It raised a Exception and said:

InvalidRequestError: One or more mappers failed to initialize – can’t proceed with initialization of other mappers. Original exception was: Class ‘models.entry.Entry’ is not mapped.

Obvious the Entry is a abstract class, which couldn’t be mapped to a real exist table. The document in official website has a example but its base class is not abstract. Now how should I do to set the polymorphic relationship with a abstract model?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T19:09:19+00:00Added an answer on May 29, 2026 at 7:09 pm

    I have found the reason of the problem and its solution.

    According to the document of sqlalchemy offical website, the abstract class could be a mapped class, because the polymorphic_union function could create a virtual table.

    I am using the declartive style model, not build mapper by hand, so the virtual table pjoin should not be created by hand. The base class AbstractConcreteBase has a method __delcare_last__ would create the pjoin with polymorphic_union function, but it would be called while the event after_configured triggering.

    The relationship with Entry in Post would be created after the Post class be generated, in this time the event after_configured have not been triggered, so __delcare_last__ function have not created the virtual table pjoin and mapped it into Entry. So the exception “Class ‘models.entry.Entry’ is not mapped.” will be raised.

    Now, I refactor the Post model, let it create the relationship with Entry in __delcare_last__ function, then it will be success because of the triggered event and the mapped Entry.

    My new implemented class like this:

    class Post(db.Model):
        """An Post."""
    
        id = db.Column(db.Integer, primary_key=True, nullable=False)
        description = db.Column(db.Unicode(140), nullable=False)
    
        @classmethod
        def __declare_last__(cls):
            cls.entries = db.relationship(Entry, viewonly=True)
    
        def attach_entries(self, entries):
            """Attach Entries To This Post.
    
            Example:
                >>> post = Post("An Interesting News", "Wow !!!")
                >>> text_entry = TextEntry(*t_args)
                >>> photo_entry = PhotoEntry(*p_args)
                >>> post.attach_entries([text_entry, photo_entry])
                >>> len(post.entries)
                2
                >>> db.session.commit()
                >>>
            """
            for entry in entries:
                self.entries.append(entry)
                entry.post = self
                db.session.add(entry)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're using interfaces to represent entity classes in our domain model. We have concrete
I'm trying to set up a TPC inheritance using Code First to model incoming
I'd like to keep my concrete classes separate from my views. Without using strongly
I am using the Table Per Subclass strategy to persist an inheritance hierarchy: alt
I have the following Hibernate Mapping, which has to be mapped using the Table
Note: All sample code is greatly simplified. I have a DLL defined as: using
How to configure Interface having multiple concrete implementation using Castle Windsor (using code). Below
I have an existing table structure that looks something like this: AnimalTable ------------- |Id
Using online interfaces to a version control system is a nice way to have
Using TortoiseSVN against VisualSVN I delete a source file that I should not have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.