I have a MySQL database where data are migrated from an Access database. The problem is that access saves boolean true value as -1, while django saves boolean true value as 1 (as tipically happens with MySQL).
So, for boolean fields, old true values are saved as -1, while new true values are saved as 1.
I need to say to django t开发者_JS百科o consider True both 1 and -1 for all boolean fields. How can I do?
Thanks in advance, Sabrina
Just update all of the old values to 1:
UPDATE <table>
SET <fieldname>=1
WHERE <fieldname>=-1
I don't have a clue what Django is, but if you did all your Boolean tests with NOT FALSE (or <>0) instead of with TRUE, it will work regardless of the actual value encoded for TRUE (-1 or 1).
Create a custom BooleanField class that extens from models.BooleanField. In the next class, true values are saved with -1 on DB.
class AccessCompatibleBooleanField(models.BooleanField):
def to_python(self, value):
if value == True:
return -1
if value == False:
return False
if value in ('t', 'True', '1', '-1'):
return -1
if value in ('f', 'False', '0'):
return False
raise exceptions.ValidationError(self.error_messages['invalid'])
If you want make filters like .filter(visibles=True) and visibles is custom boolean field, you have to add following method to your custom class.
def get_prep_value(self, value):
if value is None:
return None
b = bool(value)
if b:
return -1
return b
精彩评论