Lemayzeur
Lemayzeur

Reputation: 8525

How does Django handle the incrementation of the AutoField Primary Key?

In a Django project with postgresql, I once inserted en entry in the db, and one day. Someone else who has access to it, has manually added 36 other rows in the db with pgadmin4. When I want to add new row with the Django project, I got IntegrityError obviously, because Django tries to add 1 to the last entry id added by the Django project (This is what I think it is trying to do). Here is the traceback:

duplicate key value violates unique constraint "register_catalog_pkey"
DETAIL:  Key (id)=(2) already exists.

How to tell Django that the last entry id is 36 (the last value manually added with pgadmin4)?

I also tried to have the id field in Django Admin so I could edit it, but it did not show up.

class RegisterAdmin(admin.ModelAdmin)
    list_display_links = ['id',]
    list_display = ('id',)

Do I need to remove the primary key handled by Django, and define an IntegerField as primary key?

register_id = models.AutoField(primary_key=True)

to

register_id = models.IntegerField(primary_key=True)

Upvotes: 1

Views: 201

Answers (1)

JPG
JPG

Reputation: 88499

Use ALTER SEQUENCE command

ALTER SEQUENCE <table_name>_id_seq RESTART WITH 37

Ex: ALTER SEQUENCE myapp_register_id_seq RESTART WITH 37

Upvotes: 1

Related Questions