user2672537
user2672537

Reputation: 353

Using different database values for BooleanField in Django

I am converting an old MS Access database to a Django-based website. I've converted the data to a SQLite database, and automatically generated the models using inspectdb (which worked as well as could be expected).

It seems that MS Access stores boolean values as -1 for True and 0 for False. Rather than modify the database (it is a lot of tables!) I'm trying to subclass models.BooleanField, as follows:

class MsAccessBooleanField(models.BooleanField):
    def from_db_value(self, value, expression, connection):
        if value == -1:
            return True
        if value == 0:
            return False

    def to_python(self, value):
        if value == -1:
            return True
        if value == 0:
            return False

    def get_prep_value(self, value):

        if value == True:
            return -1
        if value == False:
            return 0
        return None

    def get_db_prep_value(self, value, connection, prepared=False):
        if value == True:
             return -1
        if value == False:
             return 0
        return None

When I view entries via the Admin interface, this seems to work (-1 values appear as Yes in the dropdown; 0 values as No).

However (this is the problem), when modifying the value and saving, I can only save as No or Unknown (selecting Yes produces a message that no value has been specified). Any idea what I might be doing wrong?

Upvotes: 0

Views: 119

Answers (1)

jackotonye
jackotonye

Reputation: 3853

You'll only need to change the BooleanField.to_python

def to_python(self, value):
    if value in (True, False):
        return bool(value)
    if value in ('t', 'True', '1', '-1'):
        return True
    if value in ('f', 'False', '0'):
        return False
    raise exceptions.ValidationError(
        self.error_messages['invalid'],
        code='invalid',
        params={'value': value},
    )

Upvotes: 2

Related Questions