Python dicts in sqlalchemy

Viewed 30925

I would like to load/save a dict to/from my sqlite DB, but am having some problems figuring out a simple way to do it. I don't really need to be able to filter, etc., based on the contents so a simple conversion to/from string is fine.

The next-best thing would be foreign keys. Please don't post links to huge examples, my head would explode if I ever set eyes on any those.

5 Answers

SQLAlchemy has a built-in JSON type that you can use:

attributes = Column(JSON)

You can simply save() method to save dicts in sqlalchemy

For example

class SomeModel(Base):
    __tablename__ = 'the_table'
    id = Column(Integer, primary_key=True)
    baked = Column(String, nullable=True)
    spam = Column(String, nullable=True)

s = {'baked': 'beans', 'spam': 'ham'})
SomeModel(**s).save()
Related