Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 764
retnuh Avatar asked Jun 03 '11 02:06

retnuh


2 Answers

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.

like image 143
neurino Avatar answered Sep 25 '22 00:09

neurino


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.

like image 26
Michael Merickel Avatar answered Sep 22 '22 00:09

Michael Merickel