Different type of SQLAlchemy column syntax

I use the SQLAlchemy recipe here to magically JSON encode / decode a column from a DB in my model, for example:

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

I hit when I wanted to create an additional "raw_data" field in my model to access the same basic JSON data, but without encoding / decoding:

    raw_data = Column("data", VARCHAR)

SQLAlchemy seems to get confused by name collision and leaves one column unmapped. Is there a way to convince SQLAlchemy to actually match both attributes to the same column?

+5
source share
1 answer

I would just define the column raw_datathrough SQLAlchemy and then use the Python / setter property for transparent use 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)
+3
source

All Articles