2009-11-22 109 views

回答

0
>>> u=User.objects.get(pk=1) 
>>> u.is_active 
1 
>>> u.is_active==1 
True 
>>> 

布爾列返回1或0的原因在您的問題的鏈接。

+0

你的例子應該是:u.is_active == True – 2009-11-22 15:11:51

+0

有沒有可能將布爾值字段隱藏爲True或False而不是1或0 – 2009-11-23 05:14:03

+0

Juanjo,我列舉了一個例子來說明如何實現True或False結果。 拉瑪,我想應該可以通過修改Django的模型代碼,但我不知道這樣的解決方案。 – fest 2009-11-23 18:41:39

5

你可以爲你的模型,評估此爲你創建你自己的方法:

class User(models.Model): 
    active_status = models.BooleanField(default=1) 

    def is_active(self): 
     return bool(self.active_status) 

那麼你對這個領域進行任何測試可能只是參考,而不是方法:

>>> u.is_active() 
True 

你可以甚至把它變成一個屬性:

class User(models.Model): 
    active_status = models.BooleanField(default=1) 

    @property  
    def is_active(self): 
     return bool(self.active_status) 

因此,類的用戶d on't甚至要知道,它是作爲一種方法來實現:

>>> u.is_active 
True 
1

這裏是適合NullBooleanField上述方法:

result = models.NullBooleanField() 

def get_result(self): 
    if self.result is None: 
     return None 
    return bool(self.result) 
1

有沒有什麼預期,這將導致不同的行爲只是一種局面基於類型?

>>> 1 == True 
True 
>>> 0 == False 
True 
>>> int(True) 
1 
>>> int(False) 
0