Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy column synonym with different type

I'm using the SQLAlchemy recipe here to magically JSON encode/decode a column from the DB in my model like:

class Thing(Base):
    __tablename__ = 'things'
    id = Column(Integer(), primary_key=True)
    data = Column(JSONEncodedDict)

I hit a snag when I wanted to create an extra "raw_data" field in my model to access the same underlying JSON data, but without encoding/decoding it:

    raw_data = Column("data", VARCHAR)

SQLAlchemy seems to get confused by the name collision and leave one column un-mapped. Is there any way I can convince SQLAlchemy to actually map both attributes to the same column?

like image 212
Mu Mind Avatar asked Oct 23 '22 10:10

Mu Mind


1 Answers

I would just define the raw_data column through SQLAlchemy and then use Python's property/setter to make transparent use of data. I.e.:

class Thing(Base):
    __tablename__ = 'things'
    id = Column(Integer(), primary_key=True)
    raw_data = Column(String())

    @property
    def data(self):
        # add some checking here too
        return json.loads(self.raw_data)

    @data.setter
    def data(self, value):
        # dito
        self.raw_data = json.dumps(value)
like image 178
Rob Wouters Avatar answered Oct 26 '22 19:10

Rob Wouters