我只是找了EveryBlock的源代码,我发现这个代码在警报/ models.py代码:Django中的属性缓存 - 有什么意义?
def _get_user(self):
if not hasattr(self, '_user_cache'):
from ebpub.accounts.models import User
try:
self._user_cache = User.objects.get(id=self.user_id)
except User.DoesNotExist:
self._user_cache = None
return self._user_cache
user = property(_get_user)
我注意到周围一堆这种模式,但我不太明白使用。整个想法是确保在自己访问FK(self = alert对象)时,你只需从db中获取一次用户对象?为什么你不只是依靠db缓存和django的ForeignKey()字段?我注意到模型定义只包含用户标识而不包含外键字段:
class EmailAlert(models.Model):
user_id = models.IntegerField()
...
任何见解将不胜感激。