user2665694
user2665694

Reputation:

sqlalchemy: filter() not properly working because of missing mapper attribute/AttributeError

My SQLAlchemy 0.8 code looks like:

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)

This gives me an AttributeError for Food.ndb_no although the Food Table contains this column 'ndb_no'. Why isn't this column mapped to the 'Food' mapper?

Upvotes: 1

Views: 421

Answers (1)

user2665694
user2665694

Reputation:

Resolved by using declarative layer and passing the Base directly to the initialize_model() method:

  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

Upvotes: 1

Related Questions