postgresql中的django迁移失败(即使是默认迁移,但在sqlite和mysql中工作)

时间:2018-01-18 05:42:58

标签: django postgresql migrate

我创建了一个新的django项目,并在setings.py

中添加了以下数据库设置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS':{'options': '-c search_path=resttest'}
    }
}

我刚刚运行" python manage.py migrate"

但是这个错误

django.db.utils.ProgrammingError: constraint "django_admin_log_user_id_c564eba6_fk" does not exist

何时尝试使用默认sqlite或MySQL更改数据库设置,它可以正常工作。 我甚至尝试使用文档中显示的'ENGINE': 'django.db.backends.postgresql'。 有人可以帮我猜出问题是什么吗?

2 个答案:

答案 0 :(得分:2)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'your_custom_database_name',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS':{'options': '-c search_path=resttest'}
    }
}

问题是您正在访问postgres数据库的默认数据库,使用其他名称创建另一个数据库并进行迁移。

答案 1 :(得分:0)

如果您使用的是Linux,请执行以下操作。安装PostgreSQL及其所需的软件包。

sudo apt-get install postgresql postgresql-contrib

以postgres用户身份登录,因为默认情况下,此用户只有在PostgreSQL中创建数据库的权限。

sudo su - postgres

现在,您以postgres用户身份登录。创建数据库用户并为其分配必要的权限。

postgres@ubuntu:~$ createuser --interactive -P
Enter name of role to add: db_user
Enter password for new role: 
Enter it again: 
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
postgres@ubuntu:~$

在上面的示例中,数据库用户名是db_user。您可以根据自己的意愿提供姓名。立即创建数据库。根据您的Django应用程序,为数据库指定一个合适的名称。

postgres@ubuntu:~$ createdb --owner db_user django_db

这里db_user是数据库用户,django_db是数据库名称。现在从postgres用户退出。

postgres@ubuntu:~$ logout

现在,我们需要配置PostgreSQL,以便它可以与Django应用程序通信。为此,请安装psycopg2数据库适配器。但是这个适配器有一些包依赖,所以首先安装它们。

sudo apt-get install libpq-dev python3-dev

现在安装,

pip install psycopg2

现在,在项目的settings.py文件中配置数据库部分。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django_db',
        'USER': 'db_user',
        'PASSWORD': '<password you entered when creating db_user>',
        'HOST': 'localhost',
        'PORT': '',                      # Set to empty string for default.
    }
}

现在,迁移数据库。

python manage.py migrate

我希望这会有所帮助。

最佳,

Dhaval

相关问题