如何通过 peewee 在 sqlite 中存储 python 列表和字典数据类型
How to store a python list and a dictionary datatype in sqlite via peewee
我在 python 中有一个列表,例如[2, 2, 4, 2, 4, 4, 2, 2, 4]。
我通过 peewee 将其存储到 "Text" 类型的 sqlite table 中。
当我从 d.b 读到这篇文章时。我得到一个字符串:
“[2, 2, 4, 2, 4, 4, 2, 2, 4]”
如果我想遍历列表,例如
value = model_risk[i]
它遍历字符,因为它是一个字符串
型号:[2、2、4、2、4、4、2、2、4]
来自数据库的值:[
来自数据库的值:2
来自数据库的值:,
来自数据库的值:<br>
来自数据库的值:2
来自数据库的值:,
来自数据库的值:<br>
来自数据库的值:4
来自数据库的值:,
所以问题是:
1.) 如何通过 peewee ORM 将列表正确存储到 sqlite
2.) 如何通过 peewee ORM 将列表正确读入 sqlite
3.) 上面关于字典类型的相同问题
更新:
现在这样做了吗:
1.) 将 SQLite 文本列中的字符串加载到 python 列表中(之前从 python 列表中存储):
if ra_obj.model_risk:
model_risk = ra_obj.model_risk.strip('[]').split(', ')
2.) 从 SQLite TEXT-columns 加载字典到 python dict(之前从 python dict 中存储):
def dict_from_str(string) -> dict:
""" Convert given string to a dictionary. """
dict_ret: dict = {}
if string:
import json
json_acceptable_string = string.replace("'", "\"")
try:
dict_ret = json.loads(json_acceptable_string)
except json.decoder.JSONDecodeError:
print("json decoder error")
return dict_ret
您可以尝试使用 ArrayField 类型(如果您使用的是 Postgres)。或者您可以使用 JSON 类型,它在 Sqlite > 3.9(我认为)和 Postgres 或最近的 MySQL.
上受支持
您可能从根本上忽略了数据库 table 就像电子表格的想法。如何在电子表格中存储数字列表?您不会将它们全部打包到一个单元格中。你将它们归一化。
我知道问题已得到解答,但由于某些兼容性原因我无法使用 JSONField 类型。我也没有理解你的第一个解决方案(似乎有点结束),所以这里有两种更简单的解决方法:
1 - 使用评估:
eval("[1,2,3,4]") = [1,2,3,4]
2 - 或者直接使用 json.loads() :
json.loads("[1,2,3,4]") = [1,2,3,4]
如果我遗漏了您的问题,请告诉我。
我在 python 中有一个列表,例如[2, 2, 4, 2, 4, 4, 2, 2, 4]。 我通过 peewee 将其存储到 "Text" 类型的 sqlite table 中。 当我从 d.b 读到这篇文章时。我得到一个字符串: “[2, 2, 4, 2, 4, 4, 2, 2, 4]”
如果我想遍历列表,例如
value = model_risk[i]
它遍历字符,因为它是一个字符串
型号:[2、2、4、2、4、4、2、2、4]
来自数据库的值:[
来自数据库的值:2
来自数据库的值:,
来自数据库的值:<br>
来自数据库的值:2
来自数据库的值:,
来自数据库的值:<br>
来自数据库的值:4
来自数据库的值:,
所以问题是: 1.) 如何通过 peewee ORM 将列表正确存储到 sqlite 2.) 如何通过 peewee ORM 将列表正确读入 sqlite 3.) 上面关于字典类型的相同问题
更新: 现在这样做了吗:
1.) 将 SQLite 文本列中的字符串加载到 python 列表中(之前从 python 列表中存储):
if ra_obj.model_risk:
model_risk = ra_obj.model_risk.strip('[]').split(', ')
2.) 从 SQLite TEXT-columns 加载字典到 python dict(之前从 python dict 中存储):
def dict_from_str(string) -> dict:
""" Convert given string to a dictionary. """
dict_ret: dict = {}
if string:
import json
json_acceptable_string = string.replace("'", "\"")
try:
dict_ret = json.loads(json_acceptable_string)
except json.decoder.JSONDecodeError:
print("json decoder error")
return dict_ret
您可以尝试使用 ArrayField 类型(如果您使用的是 Postgres)。或者您可以使用 JSON 类型,它在 Sqlite > 3.9(我认为)和 Postgres 或最近的 MySQL.
上受支持您可能从根本上忽略了数据库 table 就像电子表格的想法。如何在电子表格中存储数字列表?您不会将它们全部打包到一个单元格中。你将它们归一化。
我知道问题已得到解答,但由于某些兼容性原因我无法使用 JSONField 类型。我也没有理解你的第一个解决方案(似乎有点结束),所以这里有两种更简单的解决方法:
1 - 使用评估:
eval("[1,2,3,4]") = [1,2,3,4]
2 - 或者直接使用 json.loads() :
json.loads("[1,2,3,4]") = [1,2,3,4]
如果我遗漏了您的问题,请告诉我。