2017-01-13 117 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

相關問題