如何在Django数据库模型的字段中存储字典?

2024-09-27 19:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将此词典列表存储在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中的重复值:

enter image description here

那么,如何在数据库中存储该dict呢

我找到了这个解决方案:How to store a dictionary in a Django database model's field但是没有一个答案对我有帮助

谢谢

编辑 根据Rohith的回答,我得出以下结论:

enter image description here

但我想这样,在DB列中转换dict的每个键:

enter image description here


Tags: djangonameid数据库defaultdbdatetimedate
2条回答

使用JSON字段。请注意,SQLite中不支持它

有几种方法可以在模型中保存字典。我要提到的是JSON字段的使用

如果您使用PostgreSql作为数据库,则可以访问JSON字段。你可以在documentation上读到它。这将允许您将字典保存为Django支持的JSON文件

例如:

from django.contrib.postgres.fields import JSONField

class Creditos1(models.Model):
    dict_info = JSONField(default=dict)

在代码中

sample_dict =  [

{'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}

]

credit = Creditos1.objects.create(dict_info=sample_dict)

如果您正在使用任何其他数据库,我建议将字段创建为CharField()。然后将dict编码为JSON字符串,并将该字符串保存到Credit中。然后您可以将JSON字符串解码回来

例如:

class Creditos1(models.Model):
    dict_info = CharField(blank=True, null=True)

在代码中:

import json
sample_dict =  [
    
    {'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}
    
    ]
    encoded_json = json.dumps(sample_dict)
    credit = Creditos1.objects.create(dict_info=encoded_json)

为了获得dict的值,可以使用json.loads()

decoded_data = json.loads(credit.dict_info)
print(decoded_data[0]["name"])

更新

据我所知,函数tabla_creditos()仍然不清楚,这可能是创建多个对象的原因,甚至可能是您没有清除数据库(使用代码删除所有记录Creditos1.objects.all().delete()

如果要将字典列表保存为每个对象(假设有一个干净的DB) 您的代码:

h = some_func()
uniquefied_list = list({v['sale_id']:v for v in h}.values())
for x in range(0, len(uniquefied_list)):
    Creditos1.objects.get_or_create(name=h[x]["name"], debe=h[x]["debe"]....)

在这里,get_或_create将是更好的处理方法这里是documetation

希望这能解决你的问题

相关问题 更多 >

    热门问题