[Fixed]-Get_or_create failure with Django and Postgres (duplicate key value violates unique constraint)

12đź‘Ť

Another possible reason for these errors in get_or_create() is data type mismatch in one of the search fields – for example passing False instead of None into a nullable field. The .get() inside .get_or_create() will not find it and Django will continue with new row creation – which will fail due to PostgreSQL constraints.

👤kravietz

4đź‘Ť

I had issues with get_or_create when using postgres. In the end I abandoned the boilerplate code for traditional:

try:
    jobInvite  = Invite.objects.get(sender=employer.user, job=job)
except Invite.DoesNotExist:
    jobInvite  = Invite(sender=employer.user, job=job)
    jobInvite.save()
# end try
👤MagicLAMP

1đź‘Ť

Have you at some point had unique=True set on Visit’s profile field?

It looks like there’s been a unique constraint generated for postgres that’s still in effect. “table_visit_profile_id_key” is what it’s auto generated name would be, and naturally it would cause those errors if you’re recording multiple visits for a user.

If this is the case, are you using South to manage your database changes? If you aren’t, grab it!

0đź‘Ť

PostgreSQL behaves somewhat differently in some subtle queries, which results in IntegrityError errors, especially after you switch to Django 1.6. Here’s the solution – you need to add select_on_save option to each failing model:

class MyModel(models.Model):
     ...
     class Meta:
         select_on_save = True

It’s documented here: Options.select_on_save

👤kravietz

Leave a comment