經過一番更多的挖掘,我發現在代碼中的位置來做到這一點。
問題中的文件是Django的/ DB /模型/場/ related.py
你需要兩行加入到這個文件。
找到類「SingleRelatedObjectDescriptor」。您需要更改的功能__get __()如下:進一步
def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
return getattr(instance, self.cache_name)
except AttributeError:
raise Exception("Automated Database Fetch on %s.%s" % (instance._meta.object_name, self.related.get_accessor_name()))
# leave the old code here for when you revert!
同樣,在課堂上 「ReverseSingleRelatedObjectDescriptor」 下的代碼,你需要再次改變__get __()來:
def __get__(self, instance, instance_type=None):
if instance is None:
return self
cache_name = self.field.get_cache_name()
try:
return getattr(instance, cache_name)
except AttributeError:
raise Exception("Automated Database Fetch on %s.%s" % (instance._meta.object_name, self.field.name))
# BEWARE: % parameters are different to previous class
# leave old code here for when you revert
一旦你已經完成了這一步,您會發現Django每次執行自動數據庫查找時都會引發異常。這在第一次啓動時非常煩人,但它會幫助您追蹤那些討厭的數據庫查找。顯然,當你找到它們時,最好將數據庫代碼恢復到正常狀態。我只會建議在調試/性能調查階段使用它,而不是在現場生產代碼中使用!
對於開發,我建議你使用Django調試工具欄。它顯示查詢在數據庫中執行的詳細信息(如查詢總數和每個執行的查詢)https://github.com/robhudson/django-debug-toolbar – FallenAngel 2011-02-18 15:31:06
@FallenAngel,謝謝你的提示 - 我不會用調試工具欄之前,它是非常有用的。 – 2011-03-13 19:51:31