我有一個Attachment模型,有兩個ForeignKey欄位和一個get_attachment_path回呼,用于upload_to屬性:
def get_attachment_path(instance, filename)。
return f'{instance.owner. name}/{instance.chat.id}/{filename}'
class Attachment(models.Model)。
owner = models.ForeignKey(...)
chat = models.ForeignKey(..)
file = models.FileField(upload_to=get_attachment_path, ...)
下面一行將導致get_attachment_path的運行:
Attachment.objects.create(..., file=file)
那么,有了上面這一行,django會不會對資料庫進行兩次沖擊(一次是.create,另一次是get_attachment_path)?問這個問題是因為get_attachment_path回呼試圖訪問相關資料(instance.chat.id等)。
如果是這樣,有什么方法可以優化它嗎?
uj5u.com熱心網友回復:
不,它不會影響到資料庫,因為你已經將現有的和保存的(!) Owner和Chat物件傳遞給Attachment.objects.create,所以上傳處理器不需要從資料庫中獲取它們。
然而,當你從資料庫中獲取新的附件時,將對相關的物件進行額外的查詢:
attachment = Attachment.objects.get(id=some_id)
attachment.file.save(...)
在這種情況下,使用select_related可以洗掉額外的查詢。
你可以隨時驗證所運行的SQL查詢(僅在DEBUG模式下):
from django.db import connection
def get_attachment_path(instance, filename) 。
print('quers before', connection.quers)
path = f'{instance.owner.name}/{instance.chat.id}/{filename}'
print('quords after', connection.quords)
return path
另外,Django Debug Toolbar是Django專案中優化SQL查詢的一個重要補充。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307795.html
標籤:
下一篇:在Postgres中合并4個表
