ArKitect
ArKitect

Reputation: 87

How can I get a list of absolute image URLs from a Django QuerySet?

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?

Upvotes: 5

Views: 8771

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

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.

Example:

@property
def get_absolute_image_url(self):
    return '%s%s' % (MEDIA_URL, self.image.url)

Upvotes: 7

Related Questions