4

I have a model ModelA with a field of type ImageField. Now, I want to get all the images' urls in one go.

So, when I do ModelA.objects.all().values(), I want to get something like:

[{"id":1, "image_field": "/media/upload_folder/xyz.jpg"}, {...}]

Now, it gives something like:

[{"id":1, "image_field": "upload_folder/xyz.jpg"}, {...}]

Am I missing something?

What can I do?

3 Answers 3

6

MEDIA_URL can change, so Django doesn't store it in the database. You can prepend it yourself:

from django.conf import settings

values = ModelA.objects.all().values()
for value in values:
    value['image_field'] = settings.MEDIA_URL + value['image_field']
2
  • This gave me some idea Thanks
    – Ajay Kumar
    Nov 19, 2020 at 10:29
  • Wouldn't work if you store your images in S3 for example
    – artem
    Dec 16, 2022 at 23:14
1

The MEDIA_URL in your settings.py file is variable, so it can't add it at the beginning for you.

Loop through each object and prepend the MEDIA_URL value yourself.

for value in values:
    newURL = settings.MEDIA_URL
    newURL += value['image_field']
    value['image_field'] = newURL

Take extra care with slashes .... you dont want to end up with two together // ... it depends on whether you have one at the end of your MEDIA_URL or not.

0

You can use this way too by using Concat,Value and F

from django.db.models import F, Value
from django.db.models.functions import Concat

values = ModelA.objects.all().annotate(img_url=Concat(
    Value(settings.MEDIA_URL), F("image_field")
))

Now the img_url will have your desired output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.