python - Convert string to float SQLAlchemy -
is there way convert string float when reading database?
column size consists of string values (i.e. "45")
how value float when query db using sql alchemy.
i know easiest way float(value) if value null need deal catching exception, etc. there quick way in sqlalchemy?
example: give me float value if exists else return none
create column type conversion , database you. see documentation typedecorator.
from sqlalchemy import string sqlalchemy.types import typedecorator class stringfloat(typedecorator): impl = string def process_literal_param(self, value, dialect): return str(float(value)) if value not none else none process_bind_param = process_literal_param def process_result_value(self, value, dialect): return float(value) if value not none else none this assumes values in database either valid floats or null. if there other strings, add try block around float() call.
use type rather string or float when defining table or model.
class mymodel(base): # ... size = column(stringfloat) # ...
Comments
Post a Comment