我想将此词典列表存储在Django数据库中:
h = [
{'sale_id': 14,
'name': 'Macarena',
'fecha': datetime.date(2021, 3, 11),
'debe': 500.0},
{'sale_id': 14,
'name': 'Macarena',
'fecha': datetime.date(2021, 4, 11),
'debe': 500.0},
{'sale_id': 15,
'name': 'Yamila',
'fecha': datetime.date(2021, 4, 14),
'debe': 2000.0}
]
我试过这个:
h = tabla_creditos()
class Creditos1(models.Model):
sale_id = models.IntegerField(default=0)
name = models.CharField(max_length=150)
fecha = models.DateTimeField(default=datetime.now)
debe = models.IntegerField(default=0)
for i in range(0,len(h)):
Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe'])
其中“h”是字典,它是“tabla_creditos()”函数的结果。然后,我尝试使用“objects.create”为DB创建值,但我得到了存储在DB中的重复值:
那么,如何在数据库中存储该dict呢
我找到了这个解决方案:How to store a dictionary in a Django database model's field但是没有一个答案对我有帮助
谢谢
编辑 根据Rohith的回答,我得出以下结论:
但我想这样,在DB列中转换dict的每个键:
使用JSON字段。请注意,SQLite中不支持它
有几种方法可以在模型中保存字典。我要提到的是JSON字段的使用
如果您使用PostgreSql作为数据库,则可以访问JSON字段。你可以在documentation上读到它。这将允许您将字典保存为Django支持的JSON文件
例如:
在代码中
如果您正在使用任何其他数据库,我建议将字段创建为CharField()。然后将dict编码为JSON字符串,并将该字符串保存到Credit中。然后您可以将JSON字符串解码回来
例如:
在代码中:
为了获得dict的值,可以使用json.loads()
更新
据我所知,函数tabla_creditos()仍然不清楚,这可能是创建多个对象的原因,甚至可能是您没有清除数据库(使用代码删除所有记录Creditos1.objects.all().delete())
如果要将字典列表保存为每个对象(假设有一个干净的DB) 您的代码:
在这里,get_或_create将是更好的处理方法这里是documetation
希望这能解决你的问题
相关问题 更多 >
编程相关推荐