artem
artem

Reputation: 16777

How to get ImageField url when using QuerySet.values?

qs = self.items.values(
            ...,
            product_preview_image=F('product_option_value__product__preview_image'),
        ).annotate(
            item_count=Count('product_option_value'),
            total_amount=Sum('amount'),
        )

product_option_value__product__preview_image is an ImageField, and in the resulting QuerySet it looks like product_preview_images/photo_2022-12-10_21.38.55.jpeg. The problem is that url is a property, and I can't use media settings as images are stored in an S3-compatible storage.

Is it possible to somehow encrich the resulting QuerySet with images URLs with a single additional query, not iterating over each one?

Upvotes: 1

Views: 374

Answers (1)

Mahammadhusain kadiwala
Mahammadhusain kadiwala

Reputation: 3635

You can modify Queryset dictionary values like this...

models.py

class DEMOClass(models.Model):
      field1 = models.CharField(max_length=255, null=True,blank=True)
      field2 = models.ImageField(upload_to='Images')

      def __str__(self):
            return self.field1

views.py

def InsertData(request):
    data = DEMOClass.objects.values('field1','field2')
    print('------ Before ------')
    print(data)        
    for i in data:
        i.update({'field2':str(request.build_absolute_uri(i['field2']))})
    print('------ After ------')
    print(data) 

Output

------ Before ------
<QuerySet [{'field1': 'test', 'field2': 'Images/download_rBWYYCh.jpg'}]>
------ After ------
<QuerySet [{'field1': 'test', 'field2': 'http://127.0.0.1:8000/Images/download_rBWYYCh.jpg'}]>

Upvotes: 1

Related Questions