Django : get_or_create Raises duplicate entry with together_unique
Question:
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
Answers:
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.
Make sure your autoincrement counter is not the reason of this error.
Postgresql solution of resetting primary key autoincrement might be found here
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
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.
Make sure your autoincrement counter is not the reason of this error.
Postgresql solution of resetting primary key autoincrement might be found here