【发布时间】: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