[英]Django - why is this hitting the database twice
我的模型中有一個屬性:
def _get_image(self):
return Media.objects.get_for_object(self)
image = property(_get_image)
它在我的Media模型上調用以下函數:
def get_for_object(self, obj):
ctype = ContentType.objects.get_for_model(obj)
return self.filter(items__content_type__pk=ctype.pk, items__object_id=obj.pk)
然后在我的模板中,我正在迭代結果,如下所示:
{% if entry.image %}
<h2>Current image:</h2>
{% for m in entry.image %}
{{ m }}
{% endfor %}
{% endif %}
出於某種原因,我的SQL讀數顯示了這兩個查詢,彼此相鄰:
0.40 SELECT
EXPLAIN
Toggle Stacktrace
SELECT `media_media`.`id`, `media_media`.`file`, `media_media`.`content_type`, `media_media`.`created` FROM `media_media` INNER JOIN `media_mediaattachment` ON (`media_media`.`id` = `media_mediaattachment`.`media_id`) WHERE (`media_mediaattachment`.`content_type_id` = 12 AND `media_mediaattachment`.`object_id` = 20 )
0.38 SELECT
EXPLAIN
Toggle Stacktrace
SELECT `media_media`.`id`, `media_media`.`file`, `media_media`.`content_type`, `media_media`.`created` FROM `media_media` INNER JOIN `media_mediaattachment` ON (`media_media`.`id` = `media_mediaattachment`.`media_id`) WHERE (`media_mediaattachment`.`content_type_id` = 12 AND `media_mediaattachment`.`object_id` = 20 )
因此,每當我訪問entry.image時,數據庫都會受到攻擊。 當然它應該存儲結果或什么?
“或者其他的東西”?
為什么要存儲結果? 您已經顯式編寫了_get_image
函數,以便每次都查詢數據庫。 如果您希望它存儲結果,您需要告訴它執行此操作。
可能最簡單的方法是在模板中獲取一次:
{% with entry.image as images %}
{% if images %}
<h2>Current image:</h2>
{% for m in images %}
{{ m }}
{% endfor %}
{% endif %}
{% endwith %}
以下是如何編寫緩存屬性而不在__init__
方法中將緩存顯式設置為None
:
def _get_image(self):
if not hasattr(self, '_image'):
self._image = Media.objects.get_for_object(self)
return self._image
image = property(_get_image)
或者用更現代的語法
@property
def image(self):
if not hasattr(self, '_image'):
self._image = Media.objects.get_for_object(self)
return self._image
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.