【问题标题】:How to save a list of dictionaries as each object in a Django database model's field?如何将字典列表保存为 Django 数据库模型字段中的每个对象?
【发布时间】:2021-07-06 15:34:33
【问题描述】:

我会更好地理解我提出的问题 (How to store a dictionary in a Django database model's field?):

我有这本词典

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}

]

我想像这样将它存储在 Django 数据库 (SQLite3) 中:

但是在将此字典附加到数据库之前,我想清除数据库并避免重复值(或在将字典附加到数据库后删除重复项)

如果我选择删除重复项,我应该从“sale_id”、“name”、“fecha”和“debe”列中删除重复项,不仅从“sale_id”中删除,因为我有许多相同编号的“sale_id”但是具有不同的日期(“fecha”)。

我已经尝试过了,但每次我运行“objects.create”时,我都会在数据库中得到重复的值:

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'])

非常感谢!

【问题讨论】:

    标签: python django


    【解决方案1】:

    每次运行代码时,都会创建新对象,无论它们是否已经在数据库中。您没有提供唯一 ID。

    要删除所有对象,您只需运行即可

    Creditos1.objects.all().delete()
    

    要检查数据是否已经在数据库中以避免多次添加,例如可以使用快捷方式

    credit, created = Creditos1.objects.get_or_create(name=..., sale_id=...)
    

    编辑:一些技巧(题外话)

    顺便说一句。如果你在 python 中循环一个列表,有一种更短的方法:

    for item in h:
        Creditos1.objects.create(name=item['name'], sale_id=item['sale_id'] ...)
    

    如果密钥与您要传递的参数完全相同,您可以使用自动解压缩它们

    for item in h:
        Creditos1.objects.create(**item)
    

    综合起来:

    在运行删除命令或(重新)移动 sqlite 文件后,应该避免多次存储相同的数据。

    # models.py
    
    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)
    
    
    # view or script
    
    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}
    ]
    
    
    for item in sample_dict:
        c, new = Creditos1.objects.get_or_create(**item)
        # optional:
        if not new:
            print("Entry already in the DB:")
            print(c)
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2020-08-01
      • 2019-01-19
      相关资源
      最近更新 更多