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
然而,这看起来并不像一个伟大的方式,与内部字段搞乱。
感谢您的回答!我试图看看这是否会起作用,显然在我的Peewee版本中,它并不像那样工作。似乎在每个模型中都有一个_obj_cache字典,它包含该缓存。所以我可以在user._obj_cache:“中使用'usertype'。 – manecosta
我同意这不是很漂亮,可能会有所改变。我会拭目以待科莱菲能否提供更多支持的方法。 – manecosta