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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With