Reputation: 1218
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 ?
Upvotes: 1
Views: 543
Reputation: 6277
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
Upvotes: 1
Reputation: 1121346
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.
Upvotes: 0