【问题标题】:django.db.utils.IntegrityError: duplicate key value violates unique constraintdjango.db.utils.IntegrityError:重复键值违反唯一约束
【发布时间】:2019-07-22 09:08:54
【问题描述】:

我有国家模式

from django.db import models 

class Country(models.Model):
    country = models.CharField(max_length = 20, primary_key=True)
    country_id = models.IntegerField()

我使用以下自定义管理命令在 Country 表中上传了一些数据

from django.core.management.base import BaseCommand, CommandError
from data.models import Country
import json
from .extract_country import extracting



get_parsed_json = extracting() 

def store_data():
    for key, value in get_parsed_json['api']['countries'].items():
        country_id_field = key
        country_name = value 
        One_country = Country.objects.create(country_id = country_id_field , country = country_name)
        One_country.save()
        print(One_country)



class Command(BaseCommand):
    def handle(self, **options):
        extracting()
        store_data() 

现在我正在尝试将包含相同国家和另一个国家的扩展数据上传到 Country 表,但是当我尝试上传数据时出现以下错误。这是我的完整回溯

Traceback (most recent call last):
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "data_co
untry_name_04df4fc7_uniq"
DETAIL:  Key (country)=(Algeria) already exists.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 23, in handle
    store_data()
  File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\upload_country.py", line 14, in store_data
    One_country = Country.objects.create(country_id = country_id_field , country
 = country_name)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 413, in create
    obj.save(force_insert=True, using=self.db)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 718, in save
    force_update=force_update, update_fields=update_fields)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 748, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, upda
te_fields)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 831, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 869, in _do_insert
    using=using, raw=raw)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 1136, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\sql\co
mpiler.py", line 1289, in execute_sql
    cursor.execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 100, in execute
    return super().execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\utils.py", li
ne 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util
s.py", line 85, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "
data_country_name_04df4fc7_uniq"
DETAIL:  Key (country)=(Algeria) already exists.

我发现这是 django 用户经常遇到的问题,但没有找到解决方法。有什么建议 ?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您似乎尝试使用与您的主键相同的 county 名称创建 County。 尝试使用get_or_create():

    def store_data():
        for key, value in get_parsed_json['api']['countries'].items():
            country_id_field = key
            country_name = value 
            one_country, created = Country.objects.update_or_create(
                country_id=country_id_field
                defaults={'country': country_name},
            )
            # one_country.save() <- no need to save after create or get_or_create method.
            print(one_country)
    

    【讨论】:

    • 我尝试了你的方法,但我得到了同样的错误,但现在与国家意大利这里是追溯 django.db.utils.IntegrityError: 重复键值违反唯一约束“data_country_name_04df4fc7_uniq”详细信息:键(国家)= (意大利)已经存在。
    • 我认为如果出于某种原因 id 不同,它可能会发生。我更改了一些代码并在get_or_create 中添加了defaults,但只能通过country_name 进行查询。请重试。
    • 它工作了,但现在我在我的 country_id 有重复的值,例如我有 country_id = 26 的国家意大利和具有相同 country_id 的马来西亚
    • 在您的数据中,不同国家/地区的某些 id 似乎是相同的。因此,在我编辑答案时使用update_or_create 方法。
    • 我从 API 中提取数据,而 country_id 对于每个国家/地区都是唯一的
    【解决方案2】:

    主键必须是唯一的,如果已经存在具有“Algeria”键的实例,则不能创建具有相同键的第二个实例。

    代替:

    One_country = Country.objects.create(country_id = country_id_field , country = country_name)
    

    你可以使用get_or_create:

    # ...
    One_country, created = Country.objects.get_or_create(country=country_name)
    One_country.country_id = country_id_field
    One_country.save()
    # ...
    

    【讨论】:

    • 我尝试了你的代码,但得到了同样的错误,但在另一个国家。这是追溯 django.db.utils.IntegrityError 的过去:重复键值违反唯一约束“data_country_name_04df4fc7_uniq”详细信息:键(国家)=(意大利)已经存在。
    • 我尝试插入此代码one_country, created = Country.objects.get_or_create( country=country_name, defaults={'country_id': country_id_field}, ),然后在我的数据库中复制 country_id 字段,现在我无法尝试您的方法
    • 抱歉,我把 country 和 country_id 弄混了。它现在肯定可以工作了。
    猜你喜欢
    • 2018-03-28
    • 2013-10-08
    • 2016-04-14
    • 2018-12-06
    • 2022-11-05
    • 2014-06-19
    • 2021-01-25
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多