Logical fields in MySQL Django Models?

In Django, the logical field in MySQL is stored as TINYINT . When I get it, I get 0 or 1. Shouldn't I get False or True? Is there any way to achieve this behavior?

+4
source share
4 answers

You can create your own method for your model that will appreciate this for you:

class User(models.Model): active_status = models.BooleanField(default=1) def is_active(self): return bool(self.active_status) 

Then, any tests you run against this field can simply reference this method:

 >>> u.is_active() True 

You can even do this in the property:

 class User(models.Model): active_status = models.BooleanField(default=1) @property def is_active(self): return bool(self.active_status) 

so that class users do not even know that they are implemented as a method:

 >>> u.is_active True 
+5
source

Here is the above method adapted for NullBooleanField :

 result = models.NullBooleanField() def get_result(self): if self.result is None: return None return bool(self.result) 
+1
source

Is there a situation that you expect this to lead to type-based behavior?

 >>> 1 == True True >>> 0 == False True >>> int(True) 1 >>> int(False) 0 
+1
source
 >>> u=User.objects.get(pk=1) >>> u.is_active 1 >>> u.is_active==1 True >>> 

The reasons why logical columns return 1 or 0 are in the link in your question.

0
source

All Articles