1

I'm getting some data in JSON, where boolean values are 0 & 1.

In the postgres table is a boolean field, and expect true & false.

I try this when loading the table:

class PGBool(types.TypeDecorator):
    impl = types.BOOLEAN

    def process_result_value(self, value, dialect):
        #print value
        if value is not None:
            return bool(value)

        return value


def listen(self, table, column_info):
    type_ = column_info['type']
    print column_info['name'], type_
    if str(type_).split('.')[-1] == 'BOOLEAN':
        column_info['type'] = PGBool

    return column_info

def getTable(self, name):
    return sq.Table(
        name,
        self.meta,
        autoload=True,
        autoload_with=self.con,
        listeners=[
            ('column_reflect', listen)
        ]
    )

def saveRecord(self, table, data):
    ..
    ..
    if exist:
        self.con.execute(
            table.update().where(table.c.id == theGuid),
            data
        )
    else:
        self.con.execute(
            table.insert(),
            data
        )

But the data is not converted, and still try to insert 0 & 1.

1 Answer 1

2

when you use TypeDecorator, there's two sides to the data to be concerned with. One is the data going into the database, and the other is the data coming out. The side going in is referred to as the "bind parameters" and the side going out is the "result" data. Since you want here to deal with an INSERT, you're on the bind side, so the TypeDecorator would look like:

from sqlalchemy.types import TypeDecorator, Boolean

class CoerceToBool(TypeDecorator):
    impl = Boolean

    def process_bind_param(self, value, dialect):
        if value is not None:
            value = bool(value)
        return 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.