我使用SQLAlchemy访问一个postgres表。我想要一个查询来进行eagerloading。
from sqlalchemy.orm import sessionmaker, scoped_session, eagerload
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, Boolean, MetaData, ForeignKey
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative import declarative_base
def create_session():
engine = create_engine('postgres://%s:%s@%s:%s/%s' % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME), echo=True)
Session = scoped_session(sessionmaker(bind=engine))
return Session()
Base = declarative_base()
class Zipcode(Base):
__tablename__ = 'zipcode'
zipcode = Column(String(6), primary_key = True, nullable=False)
city = Column(String(30), nullable=False)
state = Column(String(30), nullable=False)
session = create_session()
query = session.query(Zipcode).options(eagerload('zipcode')).filter(Zipcode.state.in_(['NH', 'ME']))
#query = session.query(Zipcode.zipcode).filter(Zipcode.state.in_(['NH', 'ME']))
print query.count()
这失败了 AttributeError:'ColumnProperty'对象没有属性'mapper'
没有eagerloading的人正确地返回记录。
我是SQLAlchemy的新手。我不确定问题是什么。有什么指针吗?
答案 0 :(得分:2)
您只能在关系属性上加载。不在桌子上。预先加载意味着在获取特定对象的同时从其他表加载对象。加载查询的所有对象的方法只是添加all()。
query = session.query(Zipcode).options(eagerload('zipcode')).filter(Zipcode.state.in_(['NH', 'ME'])).all()
查询现在将是表中所有对象(行)的列表,len(查询)将为您提供计数。