Sqlalchemy does not work with pagination

六眼飞鱼酱① 提交于 2020-01-03 16:50:14

问题


I am totally new with flask and sqlalchemy. I try to make one web site just to get better understanding of flask. There are plenty of tutorials and they are mostly use sqlite. For my purpose I use postgres. and I need one page where I can use pagination. But all the time I am getting the error

AttributeError: 'Query' object has no attribute 'paginate'

my database

uri = os.environ.get('DATABASE_URL', 'postgres://login:password@127.0.0.1/db_name')
engine = create_engine(uri, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                     autoflush=False,
                     bind=engine))

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

simple model

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(Unicode(100), nullable=False)
    ...

then I use paginate

users = User.query.paginate(1, 5, False)

The same error with get_or_404() and first_or_404(). normal get or first works as usual.

I will appreciate any advice!


回答1:


You are calling paginate() on a query object provided by SQLAlchemy, but the pagination functionality is only available from a Flask-SQLAlchemy, which subclasses the base query object to add this and other features, including the get_or_404() and first_or_404() methods that you also found to not work.

All this happens because you created your database and your model using SQLAlchemy directly instead of using the facilities provided by Flask-SQLAlchemy. If you do this according to the Flask-SQLAlchemy documentation you will find that everything will work just fine.



来源:https://stackoverflow.com/questions/18409645/sqlalchemy-does-not-work-with-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!