0

I have a image table that have more than 10k images.

models.py

class Image(models.Model):
    image = models.ImageField(upload_to='image')
    tag = models.CharField(max_length=100)

views.py

Image.objects.filter(tag__icontains=tag).values('image')

By above query i am getting data in this format.

[
    {
            "image": "image/mcml4__9_ipmVd6E.jpeg",

    },
    {
            "image": "image/mcml4__df9_ipmfgdfVd6E.jpeg",

    }
]

but i need this with base url.

[

    {
            "image": "http://{{baseurl}}/media/image/mcml4__9_ipmVd6E.jpeg",

    },
    {
            "image": "http://{{baseurl}}/media/image/mcml4__9_ipmVd6E.jpeg",

    }
]

How can i do this with orm query only without manipulation in python memory.

DEEPAK KUMAR
  • 361
  • 3
  • 14
  • 1
    Please do *not* use `.values` in the first place. It is a severe anti-pattern to use this for serialization. Usually one uses a *serializer* for that: https://www.django-rest-framework.org/api-guide/serializers/ – Willem Van Onsem Dec 20 '19 at 10:51
  • 1
    and after using _serialization_, try [this](https://stackoverflow.com/questions/35522768/django-serializer-imagefield-to-get-full-url) to build the full url. – Pedram Parsian Dec 20 '19 at 10:54
  • is it possible without using serializers ?? – DEEPAK KUMAR Dec 20 '19 at 11:18
  • @DEEPAKKUMAR: exactly what is your objection againt serializers? It is a layer that can validate, encode, decode, etc. objects. By using it in an APIView, it can even remove most of the boilerplate code for most API calls (obtaining a list, obtaining details, creating a new object, etc.) – Willem Van Onsem Dec 20 '19 at 11:36

1 Answers1

1

Try to modify this snippet:

views.py

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

Image.objects.filter(tag__icontains=tag).values(image=Concat(Value('http://base_url.com', 'image', output_field=CharField())))

I haven't tried it, but it has to work.

artembo
  • 640
  • 6
  • 13