one field with different data types [SQLAlchemy]

好久不见. 提交于 2020-01-03 03:54:07

问题


I have a value that can be integer, float or string, and I created different columns:

#declarative
class MyClass(Base):

    #id and other Columns
    _value_str = Column(String(100))
    _value_int = Column(Integer)
    _value_float = Column(Float)

    def __init__(self,...,value):
        self._value_str = value if isinstance(value,(str,unicode)) else None
        self._value_int = value if isinstance(value,int) else None
        self._value_float = value if isinstance(value,float) else None

and i would like to do something like this:

>>> value = 'text'
>>> my_class = MyClass(value, ...)
>>> my_class.value
>>> 'text'
>>> session.add(my_class)
>>> session.commit()
#specialy this
>>> result = session.query(Myclass).filter(Myclass.value == 'text').one()
>>> print result.value 
>>> 'text'

Maybe i have a design problem, i accept any good idea

I'm newbe in SQLAlchemy

Thanks


回答1:


Probably a design problem - a bit of a mismatch between your DB and Python. In SQL variables (columns) have a type, whereas in python values have the type.

One possibility would be to use a single column (a string), but pickle the value before you store it.

This can be accomplished automatically with a sqlalchemy custom type.

Something along the lines of the following (uses jsonpickle to do the conversion rather than cpickle):

import sqlalchemy.types as types
import jsonpickle
from copy import deepcopy

class JsonType(types.MutableType, types.TypeDecorator):    
    impl = types.Unicode

    def process_bind_param(self, value, engine):
        return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            rv = jsonpickle.decode(value)
            return rv
        else:
            return None

    def copy_value(self, value):
        return deepcopy(value)

    def compare_values(self, x, y):
        return x == y

And then use it as follows:

class MyClass(base):
    value = Column(JsonType())


来源:https://stackoverflow.com/questions/3167842/one-field-with-different-data-types-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!