2011-08-07 38 views
26

模型例如Django的:get_or_create引发与together_unique

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的想法。

不知道这是一个错误,我打开一票https://code.djangoproject.com/ticket/16587

+0

对不起,如果不清楚的问题。我编辑了这个问题,希望现在好一点 – llazzaro

+0

只是一个普通的'get'与'get_or_create'具有相同的EXACT参数会返回该项目吗? – agf

回答

17

看来你的问题是有没有被你get_or_create多个列你不包括,见即this thread Django的邮件列表上。

您需要使用的get_or_createdefaults参数如docs描述,或对所有列指定值,get_or_create正确匹配。

+1

我明白这种类型的使用我需要默认值,但是我的get_or_create中的参数是类中可以使用的所有字段。无论如何,这些信息帮助了很多。此外,如果我删除unique_together get_or_create作品。 – llazzaro

+0

'get_or_create'也部分区分大小写 - 如果它们有不同的大小写,它不会找到匹配项,但是您可能仍然会遇到唯一性约束。 – agf

+2

我解决了阅读你的答案的问题。 DateField使用auto_now_add = True,所以我避免了我的问题中的一些重要信息。解决auto_now_add = False现在正在工作 – llazzaro

相关问题