如何从Django QuerySet获取绝对图像URL的列表? [英] How can I get a list of absolute image URLs from a Django QuerySet?
问题描述
在Django中,当您使用CDN投放媒体文件时,构造图像URL绝对路径的最佳方法是什么?在我的情况下,我有一个Movie对象的QuerySet,我想检索电影的image属性的绝对URL,其中image是ImageField。有没有办法通过使用模板标签或QuerySet API的values()函数来做到这一点?
In Django, what is the best way to construct the absolute path to an image URL when you're using a CDN to serve media files? In my case, I have a QuerySet of Movie objects, and I want to retrieve the absolute URL of the image attribute of the movie, where image is an ImageField. Is there any way to do this by using a template tag or the values() function of the QuerySet API?
推荐答案
我解决了为此,可以使用来自settings.py的MEDIA_URL值作为模型字段的url的前缀。您可以在模型上创建一个属性,将该属性返回为您想要的任何名称。
I solve this by prefixing the url for the model field with the MEDIA_URL value from settings.py. You could create a property on the model that returns this concatenated path as whatever name you'd like.
示例:
@property
def get_absolute_image_url(self):
return '%s%s' % (MEDIA_URL, self.image.url)
这篇关于如何从Django QuerySet获取绝对图像URL的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!