python - Sqlalchemy 结果后处理

标签 python orm sqlalchemy

我正在使用 Python 中的 sqlalchemy 从数据库中获取数据集:

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

然后我将迭代 View 中的 links 结果:

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

如果结果存在 pdf 文件,我想读取 linkpdf 中的外部属性。

我已经尝试过:

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

pdf 属性显然未设置。

我做错了什么?

最佳答案

添加 python 属性可能应该可以完成这项工作,例如

class Link(Base):
    ...

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

关于python - Sqlalchemy 结果后处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15222469/

相关文章:

java - Hibernate 预加载查询

python - 将 Teradata 查询读入 Pandas

symfony2 : How to remove related entity with doctrine/restrict annotation?

mysql - 使用 Propel ORM 左连接选择

python - Pika 可以在 ubuntu 上连接到 RabbitMq,但不能在 Centos 上工作?

python - 为什么我的端口未在docker-compose中映射?

具有属性约束(例如必需/可选)的 Python ORM?

python - SQLAlchemy 中查找表数据是如何声明和初始化的?

python - 计算列表中某个元素的出现次数

Python PIL.Image.convert 不使用最接近的调色板替换颜色。