Django单元测试 - 无法创建django_migrations表

时间:2018-02-02 18:47:14

标签: django postgresql django-unittest

我正在尝试编写一些单元测试并使用<div class="left-corner"></div>运行它们,但由于某种原因,脚本无法创建fixDecimals(value : string){ value = "" + value; value = value.trim(); value = parseFloat(value).toFixed(2); return value; } 表。

以下是完整错误:

manage.py test

我尝试运行here建议的django_migrations语句:

Creating test database for alias 'default'...
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
    return self.cursor.execute(sql)
psycopg2.ProgrammingError: no schema has been selected to create in
LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA...
                     ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 55, in ensure_schema
    editor.create_model(self.Migration)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 298, in create_model
    self.execute(sql, params or None)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: no schema has been selected to create in
LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA...
                     ^


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\commands\test.py", line 26, in run_from_argv
    super().run_from_argv(argv)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\commands\test.py", line 59, in handle
    failures = test_runner.run_tests(test_labels)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\test\runner.py", line 601, in run_tests
    old_config = self.setup_databases()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\test\runner.py", line 548, in setup_databases
    self.parallel, **kwargs
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\test\utils.py", line 176, in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\creation.py", line 68, in create_test_db
    run_syncdb=True,
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\__init__.py", line 141, in call_command
    return command.execute(*args, **defaults)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 91, in migrate
    self.recorder.ensure_schema()
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 57, in ensure_schema
    raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in
LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA...
                     ^
)

但我仍然得到同样的信息。我有什么想法可以解决这个问题吗?这可能是一个search_path问题吗?

更新

GRANT

我在执行grant usage on schema public to <username>; grant create on schema public to <username>; 之前尝试了~ python manage.py makemigrations users Migrations for 'users': users\migrations\0001_initial.py - Create model MyUser ~ python manage.py migrate Operations to perform: Apply all migrations: auth, contenttypes, sessions, users Running migrations: No migrations to apply. (呃!),但我仍然得到了和以前一样的错误。迁移是否已应用?我还应该提一下,我的models.py只有一个模型/表,而且它不是由Django“管理”的。

Bueller?Bueller ... Beuller ...有人吗?

5 个答案:

答案 0 :(得分:4)

我认为没有人会回答任何问题...正如我今天看到的那样,不久的将来会有人来访...因为,对于相同的错误,我做了不同的事情,没有什么不同,但我直接去了psql服务器(以我为例),并在开发期间碰到了。因此,我没有处理数据丢失问题。 选择您的数据库。然后,创建架构。

CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;

我从How can I drop all the tables in a PostgreSQL database?的最高答案中得到了答案。那样,我遇到了问题,因为我掉了所有桌子。

答案 1 :(得分:3)

我遇到了同样的错误,然后解决了。就我而言,这是因为我将Django默认模式设置为 django ,当运行 $ python manage.py test 时,测试功能试图将某些表迁移到数据库 test 模式 django ,但是尚未在其中创建模式 django 。因此,解决方案是(1)允许Django测试功能也在模式 public 中搜索,或者(2)到run unit test without a test database

从对该问题的公认答案来看,我想我的案子与该问题不同。但我认为两者都是由Django无法在搜索路径中找到架构引起的。因此,我在这里发布了我的解决方案。希望它可以帮助类似的情况。

(django-tally-QTYVOJb0) (python3.6) D:\github\django-tally>python manage.py test
Creating test database for alias 'default'...
Got an error creating the test database: database "test" already exists

Type 'yes' if you would like to try deleting the test database 'test', or 'no' to cancel: yes
Destroying old test database for alias 'default'...
Traceback (most recent call last):
  File "C:\Users\guido\.virtualenvs\django-tally-QTYVOJb0\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.InvalidSchemaName: no schema has been selected to create in
LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA...

对于解决方案(1): settings.py 中的数据库设置看起来像以前一样。

if 'RDS_HOSTNAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
            'OPTIONS': {
                'options': '-c search_path=django'
            },
            'TEST': {
                'NAME': 'test', # test database name
            },
        },
    }

现在看起来像这样。我在搜索路径中添加了 public

if 'RDS_HOSTNAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
            'OPTIONS': {
                'options': '-c search_path=django,public'
            },
            'TEST': {
                'NAME': 'test', # test database name
            },
        },
    }

答案 2 :(得分:1)

我认为它来不及回答,但是对我来说,简单的操作如下:

admin.py

答案 3 :(得分:1)

这对我有用。

CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
GRANT ALL ON SCHEMA public TO <username>;

答案 4 :(得分:0)

我最近遇到了一个类似的问题,结果发现没有为试图创建对象的用户/角色定义默认模式。为了解决该问题,我做了其中一项或两项(我不记得是哪一项):

  • 添加search_path:ALTER ROLE <user_name> SET search_path TO schema1, schema2
  • 使用currentSchema参数连接到数据库