2024-06-16 12:46:05 发布
网友
在Django,a boolean field in MySQL is stored as a TINYINT。当我找回它时,我得到0或1。我不应该是假的还是真的?有办法实现这种行为吗?
有没有一种情况,你预计这将导致不同的行为仅仅基于类型?
>>> 1 == True True >>> 0 == False True >>> int(True) 1 >>> int(False) 0
以上方法适用于NullBooleanField:
NullBooleanField
result = models.NullBooleanField() def get_result(self): if self.result is None: return None return bool(self.result)
您可以为模型创建自己的方法来计算:
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)
这样类的用户甚至不必知道它是作为一个方法实现的:
>>> u.is_active True
有没有一种情况,你预计这将导致不同的行为仅仅基于类型?
以上方法适用于
NullBooleanField
:您可以为模型创建自己的方法来计算:
然后,对该字段执行的任何测试都可以只引用该方法:
你甚至可以把它变成一个财产:
这样类的用户甚至不必知道它是作为一个方法实现的:
相关问题 更多 >
编程相关推荐