Django:get_or_create引发重复条目错误使用together_unique

37 投票
2 回答
16831 浏览
提问于 2025-04-16 23:04

模型示例

class Example(Stat):
    numeric = models.IntegerField(...) 
    date = models.DateField( auto_now_add=True,...) #auto_now_add=True was the problem

    class Meta:
       unique_together = ('numeric','date')

)

如果已经存储了72和'2011-08-07'

Example.object.get_or_create(numeric=72,date='2011-08-07')

会引发

django.db.utils.IntegrityError: (1062, "Duplicate entry '72-2011-08-07'

问题是为什么 get_or_create 会引发 IntegrityError,这正是使用 get_or_create 的目的。

不确定这是否是个bug,我已经提交了一个问题 https://code.djangoproject.com/ticket/16587

2 个回答

0

确保你的自动递增计数器不是导致这个错误的原因。

关于如何重置Postgresql中的主键自动递增,可以在这里找到解决方案。

28

看起来你的问题是因为有一些列没有包含在你的 get_or_create 里。你可以参考一下这个讨论串,这是在Django的邮件列表上提到的。

你需要使用 get_or_createdefaults 参数,具体的用法可以查看文档,或者为所有列指定值,这样 get_or_create 才能正确匹配。

撰写回答