简体   繁体   English

SQLAlchemy结果后处理

[英]Sqlalchemy results post-processing

I'm fetching a dataset from my database with sqlalchemy in Python : 我正在使用python中的sqlalchemy从数据库中获取数据集:

links = session.query(Link).order_by(Link.id.desc()).limit(20)

I'm then iterating over the links result in my view : 然后,我遍历links结果在我看来:

%for link in links:
    <div class="link">
        {{link.url}}
        %if link.pdf: 
            <a href="{{link.pdf}}">[pdf]</a>
        %end
    </div>
%end

I want to read the external attribute in link , pdf if a pdf file exists for the result. 如果要获取结果的pdf文件,我想读取linkpdf的外部属性。

I've tried : 我试过了 :

for index, link in enumerate(links):
    if os.path.isfile('/pdf/'+str(link.id)+'.pdf'):
        links[index].pdf = '/pdf/'+str(link.id)+'.pdf'
    else:
        links[index].pdf = None

but the pdf attribute is apparently not set. 但显然未设置pdf属性。

What am I doing wrong ? 我究竟做错了什么 ?

Adding a python property should probably do the job, eg 添加python属性应该可以完成这项工作,例如

class Link(Base):
    ...

    @property
    def pdf(self):
        path = '/pdf/%d.pdf' % self.id
        if os.path.isfile(path):
            return path

Generally, I'd create a list of mappings with the information needed: 通常,我会使用所需信息创建一个映射列表:

linkinfo = []
for link in links:
    pdf = '/pdf/'+str(link.id)+'.pdf'
    pdf = pdf if os.path.isfile(pdf) else None
    linkinfo.append({'url': link.url, 'pdf': pdf})

then loop over the linkinfo list in your template instead. 然后遍历模板中的linkinfo列表。

This saves having to hassle with SQLAlchemy objects and makes sure your template is handed all the right data for display. 这省去了使用SQLAlchemy对象的麻烦,并确保将模板显示的所有正确数据都交给了模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM