3

I have a model called snacks:

class Snack(models.Model):
    snack = models.CharField(max_length=9)

When I do

Snack.objects.get_or_create(snack="borsh")

I get this error:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "restaurants_snack_pkey"
DETAIL:  Key (id)=(6) already exists.

If I do it again, it's going to tell me the same thing except the key (that already exists) will be 7 and so on.

It's true that the key already exists, I'm wondering how can I make it pick a key that's the next one available?

Thanks in advance.

Jenia

Jenia Ivanov
  • 2,485
  • 3
  • 41
  • 69
  • which version of django ? if > 1.6, [check this](https://docs.djangoproject.com/en/1.6/ref/models/options/#django.db.models.Options.select_on_save) – karthikr Jun 18 '14 at 16:08
  • 1
    Is that your *full* code? Are you sure you don't have any signals, or custom save methods, or a non-automatic primary key field? – Daniel Roseman Jun 18 '14 at 17:26
  • Maybe this [link](http://stackoverflow.com/questions/5476444/django-postgres-integrity-error-duplicate-key-how-to-fix) can help you. – Salvatore Avanzo Jun 18 '14 at 19:26
  • By the way borsch is not a snack, it's a good meal :) – lehins Jun 20 '14 at 09:35

1 Answers1

2

You probably did some manual data importing, even if not, it's not problem with django, but with database auto increment sequence. Django has a management command that generates sql command to reset those:

./manage.py sqlsequencereset myapp1 myapp2

If you are using PostgreSQL you can just pipe it in like that:

./manage.py sqlsequencereset myapp1 myapp2 | psql

or mysql if you are using MySQL, but I haven't ried it.

lehins
  • 9,642
  • 2
  • 35
  • 49