Mapping Db Varchar To Domain Object Bool
How do I handle the mapping of strings in the database to bools in the domain model. Consider an example, storing coin flips in a database. For cases where there are usually only t
Solution 1:
Take a look at Augmenting Existing Types section of documentation. The following should do the trick:
import sqlalchemy.types as types
class CoinFlipDataType(types.TypeDecorator):
impl = types.String
def process_bind_param(self, value, dialect):
if value is None:
return None
assert value in (True, False)
return 'heads' if value else 'tails'
def process_result_value(self, value, dialect):
if value is None:
return None
assert value in ('heads', 'tails'), value
return value == 'heads'
def copy(self):
return CoinFlipDataType(self.impl.length)
def data_map():
mapper(Foo, db_foo, properties={'is_heads': db_foo.c.side})
db_foo = Table(
'foo', metadata,
Column('id', Integer, primary_key=True),
Column('side', CoinFlipDataType(5), nullable=False))
Post a Comment for "Mapping Db Varchar To Domain Object Bool"