[PYTHON] I defined ForeignKey to CustomUser specified in AUTH_USER_MODEL in Django, but it is not referenced

It was jammed for about 10 minutes.

Even if you google, you can't find a solution, and maybe you may have a similar problem.

Premise

I'm using Django and PostgreSQL.

I used to use the auth_user table created by default in Django, but I created a new table QiitaUser that extends the auth_user table, and now I use QiitaUser (the table name is tentative).

以前のmodels.py

from django.conf import settings
from django.db import models


class Engineers(models.Model):
    name = models.CharField(max_length=1000)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='id', on_delete=models.CASCADE, null=True)

変更後のmodels.py

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models


class Engineer(models.Model):
    name = models.CharField(max_length=1000)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='id', on_delete=models.CASCADE, null=True)


class QiitaUser(AbstractUser):
    is_owner = models.BooleanField(default=False)

settings.py

AUTH_USER_MODEL = 'QiitaUser'

Modify models and settings.py as above and execute migration to confirm that the qiitauser table is created.

The engineer table, which originally referred to the user_id of auth_user, now references the id of the qiitauser table as a foreign key (it was recognized).

Clogged

When I try to register Engineer data by specifying the id of QiitaUser ...

db=# update engineer set user_id = 10 where id = 15;
ERROR:  insert or update on table "engineer" violates foreign key constraint "engineer_user_id_xxxxxxxx_fk_auth_user_id"
DETAIL:  Key (user_id)=(10) is not present in table "auth_user".

If the id that exists in the QiitaUser table is specified in the user_id of the Engineer, an error will occur if there is no record of that id in the auth_user table.

I want you to refer to the id of QiitaUser, but I have referred to the id of auth_user.

Cause and solution

In my development environment, with the foreign key constraint on auth_user already attached, I defined a new extended table of auth_user and referred to AUTH_USER_MODEL = QiitaUser, so the foreign key constraint is auth_user and QiitaUser. It seems that both were attached and an error occurred when trying to refer to auth_user.

db=# \d engineer;
                                            Table "public.engineer"
         Column         |          Type           | Collation | Nullable |                      Default                      
------------------------+-------------------------+-----------+----------+---------------------------------------------------
 id                     | integer                 |           | not null | nextval('engineer_id_seq'::regclass)
 name                   | character varying(1000) |           | not null | 
 user_id                | integer                 |           |          | 
Indexes:
    "engineer_pkey" PRIMARY KEY, btree (id)
    "engineer_user_id_xxxxxxxx" btree (user_id)
Foreign-key constraints:
    "engineer_user_id_xxxxxxxx_fk_accounts_" FOREIGN KEY (user_id) REFERENCES accounts_visualuser(id) DEFERRABLE INITIALLY DEFERRED
 "engineer_user_id_xxxxxxxx_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED

In PostgreSQL, you can check the table definition with \ d <tablename>;.

The foreign key constraint that references the id of auth_user is no longer needed and should be removed.

db=# ALTER TABLE engineer DROP CONSTRAINT IF EXISTS engineer_user_id_xxxxxxxx_fk_auth_user_id;
ALTER TABLE

When I try to register the Engineer data again ...

db=# update engineer set user_id = 10 where id = 15;
UPDATE 1

It was a success.

If you do not define an Engineer that refers to auth_user and migrate it, but use a Model that extends auth_user at the timing of migrating for the first time after creating an Engineer, I think that the problem like this did not occur.

You need to be careful when defining and using a new CustomUser while already using auth_user.

Recommended Posts

I defined ForeignKey to CustomUser specified in AUTH_USER_MODEL in Django, but it is not referenced
NameError: global name'dot_parser' is not defined and what to do when it comes up in python
I want to specify a file that is not a character string for logrotate, but is it impossible?
I want to do it with Python lambda Django, but I will stop
I made an AI to judge whether it is alcohol or not!
I referred to it when I got stuck in the django geodjango tutorial (editing)
I want to pin Datetime.now in Django tests
[Django] Error when SlugField is specified in .filter ()
I implemented Google's Speech to text in Django
"Amazon Dash Button" has landed in Japan, but I dared to make it myself
I want to scroll the Django shift table, but ...
I want to refute "Ruby is not cool here"
How to use Decorator in Django and how to make it
I was able to repeat it in Python: lambda
I introduced black to vscode, but it doesn't autoformat
What to do when a Missing artifact occurs in a jar that is not defined in pom.xml
[VLC] How to deal with the problem that it is not in the foreground during playback
[Python] The status of each prefecture of the new coronavirus is only published in PDF, but I tried to scrape it without downloading it.