sqlalchemy 中的 Python 字典 [英] Python dicts in sqlalchemy
问题描述
我想向/从我的 sqlite 数据库加载/保存一个 dict,但是在想出一个简单的方法时遇到了一些问题.我真的不需要能够根据内容进行过滤等,因此简单地转换为/从字符串就可以了.
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.
推荐答案
您可以通过子类化 sqlalchemy.types.TypeDecorator
来创建自定义类型,以处理文本的序列化和反序列化.
You can create a custom type by subclassing sqlalchemy.types.TypeDecorator
to handle serialization and deserialization to Text.
一个实现可能看起来像
import json
import sqlalchemy
from sqlalchemy.types import TypeDecorator
SIZE = 256
class TextPickleType(TypeDecorator):
impl = sqlalchemy.Text(SIZE)
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
示例用法:
class SomeModel(Base):
__tablename__ = 'the_table'
id = Column(Integer, primary_key=True)
json_field = Column(TextPickleType())
s = SomeModel(json_field={'baked': 'beans', 'spam': 'ham'})
session.add(s)
session.commit()
这在 SQLAlchemy 文档中的一个示例,其中还展示了如何跟踪该字典的突变.
This is outlined in an example in the SQLAlchemy docs, which also shows how to track mutations of that dictionary.
这种方法应该适用于所有版本的 Python,而简单地将 json
作为值传递给 PickleType
的 pickler
参数是行不通的正确,正如 AlexGrönholm 在他对另一个答案的评论中指出的.
This approach should work for all versions of Python, whereas simply passing json
as the value to the pickler
argument of PickleType
will not work correctly, as AlexGrönholm points out in his comment on another answer.
这篇关于sqlalchemy 中的 Python 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!