【发布时间】:2018-01-18 03:48:31
【问题描述】:
我是学习 django 的新手。我使用 PostgreSQL 作为我的数据库。我创建了一个名为 gplus 的应用程序,我创建的模型看起来像这样
class Account(AbstractBaseUser):
email = models.EmailField(max_length=50, unique=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
date_of_birth = models.DateTimeField()
我应用了迁移,然后想将主键字段从默认的“id”更改为“用户名”。因此,在 psql 命令行中,我运行了以下命令
ALTER TABLE gplus_account DROP CONSTRAINT gplus_account_pkey;
ALTER TABLE gplus_account ADD PRIMARY KEY (username);
ALTER TABLE gplus_account DROP COLUMN id;
然后在models.py中,我将用户名字段编辑为
username = models.CharField(max_length=50, primary_key=true)
现在,当我尝试应用迁移时,出现错误
django.db.utils.ProgrammingError: column "id" of relation "gplus_account" does not exist
似乎 Django 需要知道表中没有“id”字段了。我该怎么做?
谢谢
【问题讨论】:
-
将用户名设为 PK 是个坏主意。 PK 应该与您的数据无关。
-
@DanielRoseman 你能详细说明为什么吗?我在网上搜索,发现为字段分配主键的唯一条件是字段中的每个数据都应该是唯一的。
标签: django postgresql