Sqlalchemy does not work with pagination

I am brand new with bulb and sqlalchemy. I am trying to make one website in order to better understand the flask. There are many tutorials, and they mainly use sqlite. For my purpose I use postgres. and I need one page where I can use pagination. But all the time I get an 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) 

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

I would be grateful for any advice!

+4
source share
1 answer

You call paginate() on the query object provided by SQLAlchemy, but pagination functionality is only available from Flask-SQLAlchemy, which subclasses the base query object to add this and other functions, including get_or_404() and first_or_404() , which you also discovered that they do not work.

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

+2
source

Source: https://habr.com/ru/post/1498652/


All Articles