The best way to store a python list to a database?

ε祈祈猫儿з 提交于 2019-12-03 15:03:34

问题


What would be the best way of storing a python list of numbers (such as [4, 7, 10, 39, 91]) to a database? I am using the Pyramid framework with SQLAlchemy to communicate to a database.

Thanks!


回答1:


Well conceptually you can store a list as a bunch of rows in a table using a one-to-many relation, or you can focus on how to store a list in a particular database backend. For example postgres can store an array in a particular cell using the sqlalchemy.dialects.postgres.ARRAY data type which can serialize a python array into a postgres array column.




回答2:


You can use json to save your arrays in db as stings:

In [1]: import json

In [2]: json.dumps([1, 2, 3])
Out[2]: '[1, 2, 3]'

In [3]: json.loads(json.dumps([1, 2, 3]))
Out[3]: [1, 2, 3]

also consider using cjson for better performances and anyjson for nice fallbacks.




回答3:


Use string(Varchar). From Zen of Python: "Simple is better than complex."




回答4:


sqlalchemy.types.PickleType can store list



来源:https://stackoverflow.com/questions/6222381/the-best-way-to-store-a-python-list-to-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!