Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url of ImageField in django query

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?

like image 923
Sandip Agarwal Avatar asked Oct 28 '25 05:10

Sandip Agarwal


2 Answers

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']
like image 102
jpic Avatar answered Oct 30 '25 12:10

jpic


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.

like image 37
DrLazer Avatar answered Oct 30 '25 12:10

DrLazer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!