[英]Resolve Django/DRF ImageField URL from F() function
我有一個用例,如果圖像 URL 存在於我們的數據庫中,我會嘗試覆蓋它。
這是通過F()
查詢獲取ImageField
的查詢集部分。
preferred_profile_photo=Case(
When(
# agent not exists
Q(agent__id__isnull=False),
then=F("agent__profile__profile_photo"),
),
default=Value(None, output_field=ImageField()),
)
Case-When 可以正確解決,但問題是從F("agent__profile__profile_photo")
返回的值不是 UI 可以使用的 URL。 相反,它類似於: "agentphoto/09bd7dc0-62f6-49ab-blah-6c57b23029d7/profile/1665342685--77e51d9c5asdf345364f774d0b2def48.jpeg"
Typically, I'd retrieve the URL via agent.profile.profile_photo.url
, but I receive the following when attempting to perform preferred_profile_photo.url
: AttributeError: 'str' object has no attribute 'url'
.
我試過包裝Value(..., output_field=ImageField())
沒有運氣。
這里的關鍵是從 F() 解析后從 ImageField 中檢索 url
作為參考,我正在使用storages.backends.s3boto3.S3Boto3Storage
。
感謝任何幫助!
我能夠使用這篇文章中的一些信息來實現這一點。
這是我用來實現的助手function:
from django.core.files.storage import get_storage_class
def get_media_storage_url(file_name: str) -> str:
"""Takes the postgres stored ImageField value and converts it to
the proper S3 backend URL. For use cases, where calling .url on the
photo field is not feasible.
Args:
file_name (str): the value of the ImageField
Returns:
str: the full URL of the object usable by the UI
"""
media_storage = get_storage_class()()
return media_storage.url(name=file_name)
Django 不會在 DB 中存儲完整的 URL。 它在代碼級別構建絕對 url。 引用自文檔:
將存儲在數據庫中的所有內容都是文件的路徑(相對於 MEDIA_ROOT)。
您可以使用build_absolute_uri()
方法獲取文件的完整 URL。 例如,您可以在序列化程序級別執行此操作:
class YourSerializer(ModelSerializer):
preferred_profile_photo = serializers.SerializerMethodField()
class Meta:
model = YourModel
fields = [
'preferred_profile_photo',
]
def get_preferred_profile_photo(self, obj):
request = self.context.get('request')
return request.build_absolute_uri(obj.preferred_profile_photo)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.