【问题标题】:How can I get image url in queryset.values()?如何在 queryset.values() 中获取图像 url?
【发布时间】:2022-06-20 12:35:13
【问题描述】:

我有一个这样的用户模型:

class CustomUser(AbstractUser):

    ...
    email = models.EmailField(unique=True) 
    profile_pic = models.ImageField(null=True, blank=True, upload_to=content_file_name)


def content_file_name(obj, filename):

    ext = filename.split('.')[-1]
    filename = "profile_pic_{0}.{1}".format(str(obj.user.id), str(ext))
    return os.path.join(filename)

我知道我可以使用user.profile_pic.url 获取 profile_pic 图像媒体路径。

但是,如何在 queryset.values() 中获取图片媒体路径?

我试过这个queryset.values("profile_pic_url")queryset.values("profile_pic__url") 但它不起作用。

我可以使用 F-Objects 对 profile_pic 进行注释,并使用 f-string 将媒体路径添加为前缀,如下所示

users = queryset.annotate(image_path=F("profile_pic")).values("image_path")
and then I can add prefix like f"/media/{user.image_path}"

【问题讨论】:

  • 您无法在 values() 查询中访问模型/字段方法或属性,为什么需要在值中包含 url?
  • @lain Shelvington 我不能将序列化程序类用于特定任务。因此,我必须使用 .values() 来检索其他一些与模型相关的数据以进行进一步验证。那么为什么我想知道是否有办法。

标签: django django-models django-views django-orm


【解决方案1】:

我认为在 values() 中没有任何方法,因为我也陷入了困境,我遇到的唯一解决方案就是这个。

product_image_url = []
for image in bundle_product_images:
    print("@@@@@@@@",image.image.url)
    product_image_url.append(image.image.url)

但如果你想在模板上使用它,那么最好的方法是使用 Jinja。

{% for image in images %}
{{image.url}}
{% endfor%}

【讨论】:

    【解决方案2】:

    我不确定在 queryset.values() 中获取图像 url,但我有另一个解决方案。

    你可以在Django模板上使用{% get_media_prefix %}得到MEDIA_URL,然后使用{{user.profile_pic}}

    例如:

    <img src="{% get_media_prefix %}{{user.profile_pic}}/>
    

    它将被渲染为

    <img src="media/<path_to_profile_pic>" />
    

    关于 {% get_media_prefix %} 的参考:Django Docs

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 2015-08-27
      • 2022-09-27
      • 1970-01-01
      • 2020-09-16
      • 2021-05-26
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      相关资源
      最近更新 更多