自从我升级到Django 2.0以来,当我运行添加外键字段的迁移时,我遇到了一个奇怪的错误
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "auth_user"
任何想法为什么?
这是我的模特课:
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)
这是它的迁移文件实例化:
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'],
},
),
以下是SQL的生成方式:
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"
我在我的数据库中重命名了一些表,并且必须通过SQL进行一些修改才能使其工作。我正在使用PostgreSQL。
我是否需要以某种方式手动添加外键约束?
auth_user表
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 ) ;
答案 0 :(得分:0)
运行alter table auth_user add constraint auth_user_id_pk primary key (id);
解决了该问题。
当我将某些模型移到另一个应用程序并手动编辑了迁移文件时,这发生在我身上。