首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >orm[‘.objects.create’]模型(attr=some_value)导致IntegrityError

问orm[‘.objects.create’]模型(attr=some_value)导致IntegrityError
EN

Stack Overflow用户
提问于 2017-09-20 01:30:40
回答 1查看 214关注 0票数 0

我的模型待办事项和实体之间是一对一的正向关系。每个待办事项都有一个实体。如果backlog缺少一个实体(它不存在于db中),我的代码会尝试创建一个实体,并将其链接到缺少该实体的backlog。

代码语言:javascript
复制
            new_entity = orm['entities.entity'].objects.create(long_name=entity_name)
            if entity_short_name is not None and entity_short_name != '':
                new_entity.name = entity_short_name
            if entity_url is not None:
                new_entity.primary_url = entity_url
            new_entity.save()
            backlog.entity = new_entity
            backlog.save()

每个实体对象都有一个称为guid的唯一ID。这是我在上面的代码中得到的错误:

代码语言:javascript
复制
django.db.utils.IntegrityError: duplicate key value violates unique constraint "entities_entity_guid_uniq"
DETAIL:  Key (guid)=(2f49223d-8732-4582-b8a1-7015f515134a) already exists.

实体模型只有一个唯一的键:

代码语言:javascript
复制
guid = models.CharField('A globally unique identifier', default = lambda: str(uuid.uuid4()), unique = True, db_index = True)

导致此完整性错误的原因可能是什么?检查数据库中是否存在具有此guid的实体将返回None

**orm是从数据库获取对象的标准django orm

代码语言:javascript
复制
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/south/management/commands/migrate.py", line 111, in handle
    ignore_ghosts = ignore_ghosts,
  File "/usr/local/lib/python2.7/dist-packages/south/migration/__init__.py", line 220, in migrate_app
    success = migrator.migrate_many(target, workplan, database)
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 254, in migrate_many
    result = migrator.__class__.migrate_many(migrator, target, migrations, database)
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 329, in migrate_many
    result = self.migrate(migration, database)
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 133, in migrate
    result = self.run(migration, database)
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 114, in run
    return self.run_migration(migration, database)
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 84, in run_migration
    migration_function()
  File "/usr/local/lib/python2.7/dist-packages/south/migration/migrators.py", line 60, in <lambda>
    return (lambda: direction(orm))
  File "/usr/local/PATH/0123__.py", line 69, in forwards
    new_entity = orm['entities.entity'].objects.create(long_name=entity_name)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 157, in create
    return self.get_queryset().create(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 322, in create
    obj.save(force_insert=True, using=self.db)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 545, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 573, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 654, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 687, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 232, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1514, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 903, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 69, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 99, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "entities_entity_guid_uniq"
DETAIL:  Key (guid)=(2f49223d-8732-4582-b8a1-7015f515134a) already exists.
EN

回答 1

Stack Overflow用户

发布于 2017-09-20 01:53:25

guid字段的问题在于,您正在将callable uuid.uuid4()的结果设置为默认值,而不是仅设置每次创建新对象时都会调用的callable,以修复:

代码语言:javascript
复制
def get_unique_id():
    return str(uuid.uuid4())

guid = models.CharField('A globally unique identifier', default=get_unique_id, unique=True, db_index=True)

完成此更改后,不要忘记运行makemigrations和migrate。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46306548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档