在Django中,MySQL中的布尔字段被存储为TINYINT。当我检索它时,我得到0或1。我不应该得到False或True吗?有没有办法实现这种行为?
class User(models.Model):
active_status = models.BooleanField(default=1)
def is_active(self):
return bool(self.active_status)
那么,您对该字段执行的任何测试只需引用该方法即可:
>>> u.is_active()
True
You can even make this into a property:
class User(models.Model):
active_status = models.BooleanField(default=1)
@property
def is_active(self):
return bool(self.active_status)
这样做的好处是,类的用户甚至不需要知道它是作为一个方法实现的:
>>> u.is_active
True
你是否预计这种情况会根据类型导致不同的行为?
>>> 1 == True
True
>>> 0 == False
True
>>> int(True)
1
>>> int(False)
0
这里是针对NullBooleanField
进行调整的上述方法:
result = models.NullBooleanField()
def get_result(self):
if self.result is None:
return None
return bool(self.result)
>>> u=User.objects.get(pk=1)
>>> u.is_active
1
>>> u.is_active==1
True
>>>