Access a column from a Flask-SQLAlchemy paginate result

假如想象 提交于 2019-12-11 05:59:46

问题


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)

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()

How can I read the text_location for the Documents I queried?


回答1:


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()


来源:https://stackoverflow.com/questions/49413062/access-a-column-from-a-flask-sqlalchemy-paginate-result

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