从原始Django SQL查询获取文件URL

问题描述

我有两个模型

class Post(models.Model):
   ...

class Postimage(models.Model):
   post = models.ForeignKey(Post)
   ...

在ListView中,我需要查询帖子和一张图片,因此最终写了一个原始查询。 我现在打的是url字段是Django尝试使用的简单路径字符串 从我的应用程序加载,而不是从MEDIA_URL加载,否则如果通过ORM加载该对象,则无法使用MEDIA_URL。

是否可以使用Django语法将该路径转换为模板中的URL?

{{ post.image.url }}

解决方法

例如,您可以获得.first() [Django-doc] PostImage并使用它来呈现图像URL:

{{ post.postimage_set.first.image.url }}

postimage_setrelated_name=… parameter [Django-doc]的默认值,如果您自己指定related_name,则应使用该名称替换postimage_set