1

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 ?

2 Answers 2

1

Adding a python property should probably do the job, e.g.

class Link(Base): ... @property def pdf(self): path = '/pdf/%d.pdf' % self.id if os.path.isfile(path): return path 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.