开发者

Strange ClassNotMappedError with sqlalchemy and Python

开发者 https://www.devze.com 2023-04-10 12:16 出处:网络
I\'m building a rather simple model using sqlalchemy, using a many-to-many relationship defined by an association table and two classes that are to be associated using the declarative syntax.

I'm building a rather simple model using sqlalchemy, using a many-to-many relationship defined by an association table and two classes that are to be associated using the declarative syntax.

When generating instances elsewhere in my code, however, I keep on getting ClassNotMappedError.

The model is defined as follows:

from database import Base

immature_product = Table('immature_products', Base.metadata,
                         Column("immature_id", Integer,
                                ForeignKey("immature_mirna.id"),
                                primary_key=True),
                         Column("mature_id", Integer,
                                ForeignKey("mature_mirna.id"),
                                primary_key=True))


class ImmatureMirna(Base):

    """A class representing an immature miRNA."""

    __tablename__ = "immature_mirna"

    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String, unique=True, nullable=False)
    mature_products = relationship("mature_mirna", secondary=immature_product,
                          backref="precursor")

    def __init__(self, name):

        self.name = name


class MirnaProduct(Base):

    """A class representing a mature miRNA."""

    __tablename__ = "mature_mirna"

    id = Column(Integer, primary_key=True, nullable=False)
    mature_id = Column(String, unique=True, nullable=False)

    def __init__(self, mature_id):
        self.mature_id = mature_id

    def __repr__(self):

        display = "<miRNA product {0} of precursor {1}"
        display = display.format(self.mature_id, self.precursor)
        return display

Base is a product of declarative_base defined in database.py as follows:

engine = create_engine(DB_URL, convert_unicode=True)
db_session = scoped_session(sessionmaker(bind=engine, autocommit=False,
                                     autoflush=False))

Base = declarative_base()
Base.query = db_session.query_property()

These are in the top level part of the module, without any function wrappers. The same module provides a function to generate the metadata:

def init_db():

    "Initializes the database."

    import models
    Base.metadata.create_all(bind=engine)

A third module, utils generates the instances. The relevant bit of code is:

for key in sorted(result):

    entry = ImmatureMirna(key)
    db_session.add(entry)

    for mature_product in result[key]:
        entry.mature_products.append(MirnaProduct(mature_product))

    db_session.commit()

The error happens the moment ImmatureMirna is called:

UnmappedClassError: Class 'Table('mature_mirna', MetaData(None), Column('id',   Integer(), table=<mature_mirna>, primary_key=True, nullable=False), Column('mature_id', String(), table=<mature_mirna>, nullable=False), schema=None)' is not mapped

A typical use of the code would be:

>>> from mymodule.database import init_db
>>> init_db()
>>> from mymodule.utils import myfunction
开发者_StackOverflow社区>>> myfunction()

However, I'm not sure where the hiccup is.


immature_product is not mapped, so the relationship within class ImmatureMirna can't be formed. Change immature_product to be a subclass of Base and I predict it will work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号