gpt4 book ai didi

django - IntegrityError 重复键值违反唯一约束 - django/postgres

转载 作者:行者123 更新时间:2023-11-29 11:05:50 24 4
gpt4 key购买 nike

我正在跟进 question that I asked earlier在其中我试图寻求从一个愚蠢/写得不好的 mysql 查询到 postgresql 的转换。我相信我成功了。无论如何,我使用的是手动从 mysql 数据库移动到 postgres 数据库的数据。我正在使用如下所示的查询:

  UPDATE krypdos_coderound cru

set is_correct = case
when t.kv_values1 = t.kv_values2 then True
else False
end

from

(select cr.id,
array_agg(
case when kv1.code_round_id = cr.id
then kv1.option_id
else null end
) as kv_values1,

array_agg(
case when kv2.code_round_id = cr_m.id
then kv2.option_id
else null end
) as kv_values2

from krypdos_coderound cr
join krypdos_value kv1 on kv1.code_round_id = cr.id
join krypdos_coderound cr_m
on cr_m.object_id=cr.object_id
and cr_m.content_type_id =cr.content_type_id
join krypdos_value kv2 on kv2.code_round_id = cr_m.id

WHERE
cr.is_master= False
AND cr_m.is_master= True
AND cr.object_id=%s
AND cr.content_type_id=%s

GROUP BY cr.id
) t

where t.id = cru.id
""" % ( self.object_id, self.content_type.id)
)

我有理由相信这很有效。然而,这导致了一个新的问题。尝试提交时,我从 django 收到一条错误消息:

IntegrityError at (some url): 
duplicate key value violates unique constraint "krypdos_value_pkey"

我已经查看了此处发布的几个回复,但我还没有完全找到解决我的问题的方法(尽管相关问题已经引起了一些有趣的阅读)。我在我的日志中看到了这一点,这很有趣,因为我从未显式调用 insert-django 必须处理它:

   STATEMENT:  INSERT INTO "krypdos_value" ("code_round_id", "variable_id", "option_id", "confidence", "freetext")
VALUES (1105935, 11, 55, NULL, E'')
RETURNING "krypdos_value"."id"

但是,尝试运行它会导致重复键错误。实际错误在下面的代码中抛出。

# Delete current coding
CodeRound.objects.filter(
object_id=o.id, content_type=object_type, is_master=True
).delete()
code_round = CodeRound(
object_id=o.id,
content_type=object_type,
coded_by=request.user, comments=request.POST.get('_comments',None),
is_master=True,
)
code_round.save()
for key in request.POST.keys():
if key[0] != '_' or key != 'csrfmiddlewaretoken':
options = request.POST.getlist(key)
for option in options:
Value(
code_round=code_round,
variable_id=key,
option_id=option,
confidence=request.POST.get('_confidence_'+key, None),
).save() #This is where it dies
# Resave to set is_correct
code_round.save()
o.status = '3'
o.save()

我已经检查了序列等,它们似乎是有序的。在这一点上,我不确定该怎么做——我认为这是 django 的问题,但我不确定。任何反馈将不胜感激!

最佳答案

这发生在我身上 - 事实证明你需要在 Postgres 中重新同步你的主键字段。关键是SQL语句:

SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1);

关于django - IntegrityError 重复键值违反唯一约束 - django/postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com