0

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?

5
  • You seem to be overriding methods that should be used to cast the value. Commented Nov 23, 2018 at 14:37
  • Sorry, can you explain? Which method should I not be overriding? Commented Nov 23, 2018 at 14:40
  • What's a lot of tables? I still think a migration would be your best bet. Commented Nov 23, 2018 at 14:47
  • 49... probably I should just do a migration anyway! Commented Nov 23, 2018 at 14:51
  • @user2672537 You'll need a string not integer. Commented Nov 23, 2018 at 16:56

1 Answer 1

2

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},
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.