How to Solve Error Message IntegrityError at /save_staff/ duplicate key value violates unique constraint “apps_staff_user_staff_id_key” DETAIL: Key (user_staff_id)=(1) already exists when running Django Application

Posted on

Introduction

Another error message which has a connection with the previous article. Precisely, it is the article ‘How to Use ModelForm to Create a Form for submitting User Input in Django Application‘. Another previous article which is also has some sort of connection, it is an article which is also focusing on solving error message in ‘How to Solve Error Message ValueError at /save_staff/ Field ‘id’ expected a number but got ”. when running Django Application‘.

Furthermore, a specific strong connection which has a  highly related error exist in ‘How to Solve Error Message ValueError at /save_staff/ Field ‘id’ expected a number but got ”. when running Django Application‘. As for the reason, actually the error in this article appear after solving the error occur in ‘How to Solve Error Message ValueError at /save_staff/ Field ‘id’ expected a number but got ”. when running Django Application‘. So, after successfully insert a new record of the staff object, inserting another row with the same user object will generate the error record in this article. Below is the error message appearance :

IntegrityError at /save_staff/

duplicate key value violates unique constraint “apps_staff_user_staff_id_key” DETAIL: Key (user_staff_id)=(1) already exists.
POST
Request URL: http://localhost:8000/save_staff/
Django Version: 4.1.1
Exception Type: IntegrityError
Exception Value:
duplicate key value violates unique constraint “apps_staff_user_id_key” DETAIL: Key (user_id)=(1) already exists.
Exception Location: C:\project\env\lib\site-packages\django\db\backends\utils.py, line 89, in _execute
Raised during: apps.views.save_staff
Python Executable: C:\project\env\Scripts\python.exe
Python Version: 3.10.5
Python Path: [‘C:\\project\\model’,
‘C:\\python\\python310\\python310.zip’,
‘C:\\python\\python310\\DLLs’,
‘C:\\python\\python310\\lib’,
‘C:\\python\\python310′,
C:\\project\\env’,
‘C:\\project\\env\\lib\\site-packages’]
Server time: Sat, 17 Sep 2022 15:26:47 +0000

As for the Django project structure which is generating the error message exist below :

(env) C:\project>dir
Volume in drive C is Windows-SSD
Volume Serial Number is CA30-19A4

Directory of C:\project

09/06/2022 07:13 AM <DIR>          .
09/06/2022 10:42 AM <DIR>          ..
09/06/2022 08:19 PM <DIR>          apps
08/24/2022 09:30 AM        159,744 db.sqlite3
08/20/2022 05:17 PM            683 manage.py
08/20/2022 05:18 PM <DIR>          project
09/06/2022 07:14 AM            126 requirements.txt
3 File(s) 160,553 bytes
4 Dir(s) 65,556,508,672 bytes free

(env) C:\project> 

In case of the Django application structure, it is exist in the ‘apps’ folder exist below :

(env) C:\project> cd apps
(env) C:\project\apps>dir
Volume in drive C is Windows-SSD
Volume Serial Number is CA30-19A4

Directory of C:\project\apps

09/06/2022 08:19 PM <DIR>       .
09/06/2022 07:13 AM <DIR>       ..
08/24/2022 10:02 AM         215 admin.py
08/24/2022 08:43 AM         146 apps.py
09/17/2022 02:18 PM         454 forms.py
08/26/2022 02:19 PM <DIR>       migrations
08/26/2022 02:05 PM       1,548 models.py
09/06/2022 07:01 PM <DIR>       templates
08/24/2022 08:43 AM          63 tests.py
09/06/2022 08:03 AM         118 urls.py
09/08/2022 06:43 AM         871 views.py
08/24/2022 08:43 AM           0 __init__.py
09/08/2022 06:43 AM <DIR>       __pycache__
7 File(s) 2,961 bytes
6 Dir(s) 66,276,225,024 bytes free

(env) C:\project\apps>

How to Solve Error Message IntegrityError at /save_staff/ duplicate key value violates unique constraint “apps_staff_user_staff_id_key” DETAIL: Key (user_staff_id)=(1) already exists

Solving the error message for this article will have the same solution with the one available in the previous article. In the previous article which is ‘How to Solve Error Message ValueError at /save_staff/ Field ‘id’ expected a number but got ”. when running Django Application‘, the solution is modifying a model for defining staff object. Precisely, it is modifying the attribute of a model. It is changing from models.OneToOneField into models.ForeignKey for the user attribute. Below is the actual content of the ‘Staff’ class exist in ‘models.py’ file :

class Staff(models.Model):
    id_unique = models.AutoField(primary_key=True)
    user_staff = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True, default=None)
    name = models.CharField(max_length=255, default="")
    department = models.OneToOneField(Department, on_delete=models.CASCADE, null=True, blank=True, default=None)
    unit = models.OneToOneField(Unit, on_delete=models.CASCADE, null=True, blank=True, default=1)

    def __str__(self):
        return '%s' %(self.name)

Actually, in this context, the error appear after submitting a form for the second time in order to add a new object of ‘staff’ as follows :

How to Solve Error Message IntegrityError at /save_staff/ duplicate key value violates unique constraint "apps_staff_user_staff_id_key" DETAIL: Key (user_staff_id)=(1) already exists when running Django Application
How to Solve Error Message IntegrityError at /save_staff/ duplicate key value violates unique constraint “apps_staff_user_staff_id_key” DETAIL: Key (user_staff_id)=(1) already exists when running Django Application

Before submitting the above form in order to add or to create a new object of staff, there is already a previous process for adding a new object of staff which ends in a success. So, in this case, there is already a staff object which is mapped with one object of ‘User’ represented by ‘user_staff’ variable as its attribute. Unfortunately, in the second attempt for adding another different staff object but using the same ‘User’ object of ‘admin’, it triggers the error message. So, the type of ‘models.OneToOneField’ for User object in this example does not allow that one object User to be shared by more than one ‘Staff’ object.

After submitting the form in the second time, looking in the error message, it involves duplicate key value. In this case, the id of the attribute ‘user_staff’ will be considered as a duplicate key value which will violates unique constraint “apps_staff_user_id_key”. The reason is also exist as part of the error message which is ‘DETAIL: Key (user_id)=(1) already exists’.  As for the solution, it is enough just by modifying the Staff class as in the above definition. Especially, modifying the attribute which has the type of model.OneToOneField as follows :

class Staff(models.Model):
    id_unique = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default=None)
    name = models.CharField(max_length=255, default="")
    department = models.OneToOneField(Department, on_delete=models.CASCADE, null=True, blank=True, default=None)
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE, null=True, blank=True, default=None)

    def __str__(self):
        return '%s' %(self.name)

Drop the previous Staff object before and then migrate the database to implement the changes in the Staff models. After that, just run the Django application once more. If there are no further error message appear, the Django application will run properly.

One thought on “How to Solve Error Message IntegrityError at /save_staff/ duplicate key value violates unique constraint “apps_staff_user_staff_id_key” DETAIL: Key (user_staff_id)=(1) already exists when running Django Application

Leave a Reply