talkingtoaj
talkingtoaj

Reputation: 888

Unable to add some foreign key fields

I'm getting an odd error when I run migrations that add foreign key fields ever since I upgraded to Django 2.0

django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "auth_user"

Any ideas why?

This is my model class:

class Tag(models.Model):
    """
    """
    titles = models.ManyToManyField('main.Sentence')
    parent = models.ForeignKey('Tag',null=True,blank=True, on_delete=models.SET_NULL)
    author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    created = models.DateTimeField(auto_now_add=True)

This is the migration file instantiation of it:

    migrations.CreateModel(
        name='Tag',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('created', models.DateTimeField(auto_now_add=True)),
            ('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
            ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='coach.Tag')),
            ('titles', models.ManyToManyField(to='main.Sentence')),
        ],
        options={
            'ordering': ['-created'],
        },
    ),

And here's how the SQL is generated:

ALTER TABLE "coach_tag" ADD CONSTRAINT "coach_tag_author_id_6e9296b3_fk_auth_user_id" FOREIGN KEY ("author_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED;

SQL Error [42830]: ERROR: there is no unique constraint matching given keys for referenced table "auth_user"
  org.postgresql.util.PSQLException: ERROR: there is no unique constraint matching given keys for referenced table "auth_user"

I did rename some tables in my DB and had to do some modification via SQL to make things work. I'm using PostgreSQL.

Do I need to add foreign key constraint manually somehow?

auth_user table

CREATE TABLE public.auth_user ( 
    id int4 NOT NULL DEFAULT nextval('auth_user_id_seq'::regclass), 
    password varchar(128) NOT NULL, 
    last_login timestamptz NULL, 
    is_superuser bool NOT NULL, 
    username varchar(150) NOT NULL, 
    first_name varchar(30) NOT NULL, 
    last_name varchar(150) NOT NULL, 
    email varchar(254) NOT NULL, 
    is_staff bool NOT NULL, 
    is_active bool NOT NULL, 
    date_joined timestamptz NOT NULL 
) WITH ( OIDS=FALSE ) ;

Upvotes: 2

Views: 1095

Answers (1)

Wariored
Wariored

Reputation: 1343

Running alter table auth_user add constraint auth_user_id_pk primary key (id);fixes the problem. This happened to me when I've moved some Models to another app and manually edited migrations files.

Upvotes: 1

Related Questions