2017-01-13 118 views
0

比方说,我有一个User模型,它有一个指向Usertype的外键。有没有办法检查模型字段是否被提取?

如果我只是检索我的用户而不加入Usertype表,那么当我最终访问它时,会有额外的查询来检索该Usertype。

我的问题是,如果有办法来检查这个领域是否已经填补,或者如果我的访问将触发一个提取。

事情是这样的:

class Usertype(BaseModel): 
    name = CharField(max_length=32) 

    def serializable(self): 
     return { 
      'name': self.name 
     } 

class User(BaseModel): 
    name = CharField(max_length=32) 
    usertype = ForeignKeyField(Usertype) 

    def serializable(self): 
     ret = { 
      'name': self.name, 
     } 

     if self.usertype: 
      ret['usertype'] = self.usertype.serializable() 

     return ret 

如果我不喜欢这样,我的假设是,if语句将导致读取的情况发生。

更新:

从塔拉斯回答我能弄清楚,有对车型_obj_cache属性,保存缓存的相关对象。 因此,我可以实现我想:

def serializable(self): 
    ret = { 
     'name': self.name, 
    } 

    if 'usertype' in self._obj_cache: 
     ret['usertype'] = self.usertype.serializable() 

    return ret 

然而,这看起来并不像一个伟大的方式,与内部字段搞乱。

回答

1

嗯,从技术上说 - 是的,有办法,但不是你想要的选择。 我正在挖掘代码,发现数据缓存的地方。如果你检查线#382你会看到下面的代码:

# The related instance is loaded from the database and then cached in 
# the attribute defined in self.cache_name. It can also be pre-cached 
# by the forward accessor (ForwardManyToOneDescriptor). 
try: 
    rel_obj = getattr(instance, self.cache_name) 
except AttributeError: 
    related_pk = instance._get_pk_val() 

什么是说的是“我要去,除非它存在于缓存从数据库中获取价值。什么是缓存的名称? - 你的情况是u'_usertype_cache'。这里是一个证明: enter image description here

所以,从技术上说 - 是的,有一种方法。你真的想使用受保护的领域并添加自己的黑客?我不会。

+0

感谢您的回答!我试图看看这是否会起作用,显然在我的Peewee版本中,它并不像那样工作。似乎在每个模型中都有一个_obj_cache字典,它包含该缓存。所以我可以在user._obj_cache:“中使用'usertype'。 – manecosta

+0

我同意这不是很漂亮,可能会有所改变。我会拭目以待科莱菲能否提供更多支持的方法。 – manecosta

相关问题