简体   繁体   中英

Sqlalchemy results post-processing

I'm fetching a dataset from my database with sqlalchemy in Python :

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

I'm then iterating over the links result in my view :

%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.

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.

What am I doing wrong ?

Adding a python property should probably do the job, eg

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.

This saves having to hassle with SQLAlchemy objects and makes sure your template is handed all the right data for display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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