sqlalchemy不与分页工作 [英] Sqlalchemy does not work with pagination
问题描述
$ p $
AttributeError:'查询'对象没有属性'分页'
我的数据库
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))
ase = declarative_base()
Base.query = db_session.query_property()
简单模型
$ $ $ $ $ code $ c $> b
$ b $ (100),nullable = False)
...
然后我使用paginate
users = User.query.paginate(1,5,False)
与get_or_404()和first_or_404()相同的错误。正常获得或第一次照常工作。
我将不胜感激任何建议!
您正在对由SQLAlchemy提供的查询对象调用 paginate()
,但分页功能只能从Flask-SQLAlchemy中获得,它将基本查询对象添加这个和其他功能,包括你也发现不能工作的 get_or_404()
和 first_or_404()
。
所有这一切都是因为您直接使用SQLAlchemy创建了数据库和模型,而不是使用Flask-SQLAlchemy提供的工具。如果你按照Flask- SQLAlchemy文档来做到这一点,你会发现一切都会正常工作。 / p>
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!
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.
这篇关于sqlalchemy不与分页工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!