django 使用QuerySet.values时如何获取ImageField的url?

ruarlubt  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(103)
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是一个ImageField,在结果QuerySet中看起来像product_preview_images/photo_2022-12-10_21.38.55.jpeg。问题是url是一个属性,我不能使用media设置,因为图像存储在S3兼容的存储中。
有没有可能通过一个额外的查询,而不是对每个查询进行迭代,用图像URL来丰富结果QuerySet?

k4aesqcs

k4aesqcs1#

您可以像这样修改Queryset字典值...

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)

输出

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

相关问题