37

model example

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')

)

If 72 and '2011-08-07' is already stored

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

raises

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

the question is why get_or_create raises the IntegrityError, thats the idea of using get_or_create.

Not sure if this is a bug, I opened a ticket https://code.djangoproject.com/ticket/16587

agf
  • 171,228
  • 44
  • 289
  • 238
llazzaro
  • 3,970
  • 4
  • 33
  • 47

2 Answers2

28

It appears your problem is with there being more columns you're not including in your get_or_create, see i.e. this thread on a Django mailing list.

You need to use the defaults parameter of get_or_create as described in the docs, or specify values for all columns, for get_or_create to match correctly.

agf
  • 171,228
  • 44
  • 289
  • 238
  • 1
    I understand that type of use I would need defaults,but my params in get_or_create are the entire fields avaidable in the class. Anyways that information helped a lot. Also if I remove the unique_together the get_or_create works. – llazzaro Aug 08 '11 at 01:43
  • `get_or_create` is also partially case sensitive -- if they have different case, it won't find the match, but you might still hit the uniqueness constraint. – agf Aug 08 '11 at 02:45
  • 3
    I solved the problem reading your answer. DateField was using auto_now_add=True , so I avoided some important information in my question. To solve auto_now_add=False is working now – llazzaro Aug 08 '11 at 12:35
  • The part of the defaults is often skipped over, and is a common source of errors. – snakesNbronies May 02 '13 at 05:51
  • 1
    @llazzaro Why can't 'DateField was using auto_now_add=True' be added to your defaults? – nu everest May 04 '14 at 01:10
  • 3
    I'm setting my defaults and still getting this integrity error :/ – Blairg23 Feb 02 '18 at 06:05
0

Make sure your autoincrement counter is not the reason of this error.

Postgresql solution of resetting primary key autoincrement might be found here

techkuz
  • 3,608
  • 5
  • 34
  • 62