从Flask-SQLAlchemy分页结果访问列 [英] Access a column from a Flask-SQLAlchemy paginate result

查看:123
本文介绍了从Flask-SQLAlchemy分页结果访问列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Document模型有一个text_location列,这是我在查询后需要从中读取的文件路径.我在查询时使用paginate.

My Document model has a text_location column, a file path that I need to read from after querying. I am using paginate when querying.

是通过以下代码创建的:

That is created through this code:

class Document(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text_location = db.Column(db.String)

page_views = Document.query.paginate(page, 1, False)

我可以在模板中正确显示{{ page_views }}.但是,如果尝试打开text_location,则会得到"Pagination" object has no attribute "text_location".

I can display {{ page_views }} correctly in the template. However, if I try to open text_location, I get "Pagination" object has no attribute "text_location".

with open(page_views.text_location) as f:
    document_text = f.read()

如何阅读查询的Documentstext_location?

推荐答案

Flask-SQLAlchemy的 Pagination 对象.检索到的项目列表在 items 属性中.遍历items以获得单个模型结果.

Flask-SQLAlchemy's paginate method returns a Pagination object. The list of items retrieved is in the items attribute. Iterate over items to get individual model results.

pager = Document.query.paginate()

for document in pager.items:
    with open(document.text_location) as f:
        document.text = f.read()

这篇关于从Flask-SQLAlchemy分页结果访问列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆