【问题标题】:Django admin inline duplicate key value violates unique constraintDjango admin 内联重复键值违反唯一约束
【发布时间】:2018-09-06 23:01:45
【问题描述】:

Python 3.6 Django 2.0

我有两个模型:

from django.contrib.contenttypes.fields import GenericRelation

@python_2_unicode_compatible
class Domain(models.Model):
    tool_result = GenericRelation('projects.ToolResult')


@python_2_unicode_compatible
class ToolResult(models.Model):
    tool = models.ForeignKey('projects.Tool', on_delete=models.CASCADE)
    class Meta:
        unique_together = ('content_type', 'object_id', 'tool')

然后在管理类中创建通用表格内联:

class ToolResultGenericTabularInline(GenericTabularInline):
    model = ToolResult
    extra = 0

@admin.register(Domain)
class DomainAdmin(admin.ModelAdmin):
    inlines = [ToolResultGenericTabularInline, ]

当我尝试通过内联保存相同的对象时,出现错误:

重复键值违反唯一约束 “projects_toolresult_content_type_id_object_i_71ee2c2e_uniq”详细信息: 键 (content_type_id, object_id, tool_id)=(18, 22, 3) 已存在。

这是一个 django 错误吗?

【问题讨论】:

  • 您尝试过使用新数据库吗?
  • 是的,当我不是通过内联创建对象时,它工作正常

标签: python django


【解决方案1】:

在 ToolResult 类的元描述中:

class Meta:
        unique_together = ('content_type', 'object_id', 'tool')

unique together 行表示 ToolResults 中的每个工具都应该是唯一的。如果您删除此 unique_together 约束,您将能够保存相同的对象。 我希望这个对你有用。

【讨论】:

  • 但我需要每个工具只有一个工具结果,'content_type','object_id'
  • 例如,如果我有,则不能有重复项:tool = google content_type='Domain' object='1'
  • 我认为这确实可能是与 django 相关的问题,然后正如 Jibin 建议的那样:code.djangoproject.com/ticket/13091
【解决方案2】:

查看here

Django 票 #12028

【讨论】:

  • 但它说它关闭了
猜你喜欢
  • 2016-06-12
  • 2016-11-27
  • 2018-03-14
  • 2012-12-31
  • 1970-01-01
  • 2011-06-26
  • 2015-03-01
  • 2012-06-20
相关资源
最近更新 更多