sqlalchemy:filter()由于缺少mapper属性/ AttributeError而无法正常工作

时间:2013-01-06 11:05:23

标签: python sqlalchemy

我的SQLAlchemy 0.8代码如下:

model.py:

from sqlalchemy import Table
from sqlalchemy.orm import mapper

class Food(object):
    pass

def initialize_model(metadata):
    FoodTable = Table('food', metadata, schema='food', autoload=True)
    globals()['Food'] = mapper(Food, FoodTable)

app.py

engine = create_engine(dsn, convert_unicode=True)$
metadata = MetaData(engine)$

import xxx.core.model$
xxx.core.model.initialize_model(metadata)$

session = scoped_session(sessionmaker(bind=engine, twophase=True))

from xxx.core.model import Food
results = session.query(Food).filter(Food.nbo_no==query)

这为Food.ndb_no提供了一个AttributeError,尽管Food Table包含了这个 列'ndb_no'。为什么这个列没有映射到'Food'映射器?

1 个答案:

答案 0 :(得分:1)

通过使用声明层并将Base直接传递给initialize_model()方法来解决:

  9 def initialize_model(Base):
 10     
 11     class Food(Base, Mixin):
 12         __tablename__ = 'food'
 13         __table_args__ = {'schema': 'food', 'autoload': True}
 14     globals()['Food'] = Food