Ошибка отношение уже существует django

I’m trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:

python manage.py makemigrations crud

Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))

python manage.py migrate crud

Operations to perform:
  Apply all migrations: crud
Running migrations:
  Applying crud.0001_initial...Traceback (most recent call last):
  File "manage.py", line 18, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 82, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "crud_crudpermission" already exists

Some highlights from the migration file:

dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

,

The crud app is not meant to actually do anything, but I use it another app, so when I try migrate from that app, I trigger the above problem.

I’ve found other examples on the web of people with similar issues, but none of their cases seem to apply because

  1. The problem affects an entire relation, not just one column
  2. I am not using multiple inheritance.

Where should I look next to find the underlying problem?

Usually this relation x already exists problem appears when you’ve applied the change at some point in the database, but the Django migrations system hasn’t got a clue about the fact that you already did that. How could it happen? For example if you add a ForeignKey field to your model, make a migration, migrate it, but then change your mind and delete the migration without migrating backwards before that. Nothing breaks in the project, but the relationship and the field in the database remain (you might run into trouble, if the field is non-nullable). Now if you change your mind again and decide that shiiit, I needed that field anyhows and add it again, make a new migration and try to migrate it, then you get the relation x already exists error.

Ok, what then? Usually the simplest way is to fake the failing migration, but BEWARE that if you have any other unapplied changes in the migrations, then those won’t be applied to the database either. Before you start faking migrations, make sure that you understand what and why you are faking. Ideally you’d have only one AddField in the migration file that is soon to be faked, because otherwise all changes in the migration file will be faked (faking migrations means, that the changes are not applied to database, but Django will consider them done).

If you have two unapplied migrations, then you definitely shouldn’t run migrate --fake without specifying the migration number, because then the latter unapplied migration will be unapplied as well. It SEEMS in your case, that running manage.py migrate 0002 --fake and manage.py migrate afterwards might fix everything, but without knowing everything about what you’ve done, it’s impossible to say for certain.

If I picked up your project, here’s what I would do:
1) Check if 0002 contains more than one change.
If yes, then copy everything except the failing field to 0003.
If no, then proceed to manage.py migrate 0002 --fake.
2) Run manage.py migrate again to migrate 0003.

Answer by Isaiah Best

Jobs
Programming & related technical career opportunities

,

How common was programming in C targeting 8-bit processors in 1983?

,revert models.py to what it was and only introduce the new
relationship that appears to already exist in models.py.,comment out the relationship in models.py

This works pretty fine

./manage.py migrate --fake default

Answer by Addilynn Barker

Recently we have just had to wipe and re-start our migrations due to some hardware complications and it has come up that we cannot simply re-generate migration files as Django will attempt to re-create all migration files and all models from scratch. Obviously this is kicking up a django.db.utils.ProgrammingError: relation «<Table_Name_Here>» already exists which is not very easily fixable.
,Django Users Mailing List,Getting Started with Django,
Is there a reason why you can’t regenerate your migrations from scractch and simply run migrate —fake?

Problem

I am stuck in a situation where we maintain development and deployment environments, each with slightly different migrations due to error and bug fixing and the fact that the DB is not backed up to the dev environment. As a result, we do not track/sync migration files between the two as they would not be compatible with the tracked files in each DB. Recently we have just had to wipe and re-start our migrations due to some hardware complications and it has come up that we cannot simply re-generate migration files as Django will attempt to re-create all migration files and all models from scratch. Obviously this is kicking up a django.db.utils.ProgrammingError: relation "<Table_Name_Here>" already exists which is not very easily fixable.

django.db.utils.ProgrammingError: relation "<Table_Name_Here>" already exists

Answer by Benjamin Lindsey

Successfully merging a pull request may close this issue.,More our documentation was lacking here, I’ve just added the instructions: http://docs.weblate.org/en/latest/admin/upgrade.html#upgrade-from-1-9-to-2-0,

Discussions
,

Discussions

$ ./manage.py syncdb
Syncing...
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Synced:
 > django.contrib.auth
 > django.contrib.contenttypes
 > django.contrib.sessions
 > django.contrib.sites
 > django.contrib.messages
 > django.contrib.staticfiles
 > django.contrib.admin
 > django.contrib.admindocs
 > django.contrib.sitemaps
 > south
 > weblate

Not synced (use migrations):
 - social.apps.django_app.default
 - weblate.trans
 - weblate.lang
 - weblate.accounts
(use ./manage.py migrate to migrate these)

Answer by Alessandro Collins

I’m trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:,The crud app is not meant to actually do anything, but I use it another app, so when I try migrate from that app, I trigger the above problem.,I’ve found other examples on the web of people with similar issues, but none of their cases seem to apply because,Previous story error TS2346: Supplied parameters do not match any signature of call target

python manage.py makemigrations crud
Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))
python manage.py migrate crud
dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

Answer by Callie Fields

Some of the answers at django.db.utils.ProgrammingError: relation already exists seem to be pretty drastic, like deleting all migrations or using the command option —fake, without providing an explanation of what fundamentally is causing the error.,It seems ‘innocent enough’, but when I try to migrate, I get the following ProgrammingError:,Following the instructions, I ran makemigrations to create them:,If you add any files,it will delete all existing files related to this question-(questions only answer remains unchanged)

I recently checked out the master branch of a project, and there were model changes not yet reflected in a migration:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  No migrations to apply.
  Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

Following the instructions, I ran makemigrations to create them:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py makemigrations
Migrations for 'auth':
  venv/lib/python3.6/site-packages/django/contrib/auth/migrations/0009_auto_20180425_1129.py
    - Alter field email on user
Migrations for 'lucy_web':
  lucy_web/migrations/0146_auto_20180425_1129.py
    - Alter field description on sessiontype
    - Alter field short_description on sessiontype

Interestingly, the 0009_auto_20180425_1129.py migration was created in the venv containing Django’s source code (version 1.11.9), which I don’t believe anyone on our team changed. Here is this migration:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-04-25 18:29
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0008_alter_user_username_max_length'),
    ]

    operations = [
        migrations.AlterField(
            model_name='user',
            name='email',
            field=models.EmailField(blank=True, max_length=254, unique=True, verbose_name='email address'),
        ),
    ]

It seems ‘innocent enough’, but when I try to migrate, I get the following ProgrammingError:

(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auditlog, auth, contenttypes, lucy_web, oauth2_provider, otp_static, otp_totp, sessions, two_factor
Running migrations:
  Applying auth.0009_auto_20180425_1129...Traceback (most recent call last):
  File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "auth_user_email_1c89df09_uniq" already exists

Answer by Emersyn McKay

django — South migration error — relationship already exists
,
identifier — PostgreSQL error: relationship already exists
,
Django 1.8 cannot be executed django.db.utils . programmingerror: relationship «auth»_ «User» does not exist
,
python — stay manage.py During testing“ django.db.utils . programmingerror: relationship «app»_ «User» does not exist“

python manage.py makemigrations crud

Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))

Some highlights from the migration file:

dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

Answer by Charles Weaver

django.db.utils.ProgrammingError: relation «app_model_user_id_be6c80b4» already exists,(Of course, app and model are the names of my actual app and model),Drop all of the tables in the offending app,In my migrations, I create a new model and a ForeignKey to that model from an old model. When I try to run these migrations, I get the following error:

In my migrations, I create a new model and a ForeignKey to that model from an old model. When I try to run these migrations, I get the following error:

django.db.utils.ProgrammingError: relation "app_model_user_id_be6c80b4" already exists

django.db.utils.ProgrammingError: relation "app_model_user_id_be6c80b4" already exists

Answer by Everest Benson

原文
标签

python

django

postgresql

ubuntu

,关于python — django.db.utils.ProgrammingError : relation already exists,我们在Stack Overflow上找到一个类似的问题:

https://stackoverflow.com/questions/29830928/

,
postgresql — hadoop-大型数据库查询
,我正在尝试为新的 django 项目设置表(即,数据库中尚不存在这些表); django 版本是 1.7,数据库后端是 PostgreSQL。该项目的名称是 crud。迁移尝试的结果如下:python manage.py makemigrations crud

我正在尝试为新的 django 项目设置表(即,数据库中尚不存在这些表); django 版本是 1.7,数据库后端是 PostgreSQL。该项目的名称是 crud。迁移尝试的结果如下:
python manage.py makemigrations crud

Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))

dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

这很好用

./manage.py migrate --fake default

Я пытаюсь настроить таблицы для нового проекта django (то есть таблицы НЕ уже существуют в базе данных); версия django — 1.7, а конец db — PostgreSQL. Название проекта красное. Результаты попытки миграции:

python manage.py makemigrations crud

Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))

python manage.py migrate crud

Operations to perform:
  Apply all migrations: crud
Running migrations:
  Applying crud.0001_initial...Traceback (most recent call last):
  File "manage.py", line 18, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 82, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "crud_crudpermission" already exists

Некоторые основные моменты из файла миграции:

dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

Приложение crud не предназначено, чтобы на самом деле ничего делать, но я использую его в другом приложении, поэтому, когда я пытаюсь выполнить миграцию из этого приложения, я запускаю вышеупомянутую проблему.

Я нашел другие примеры в Интернете людей с подобными проблемами, но ни один из их случаев не применяется, потому что

  • Проблема затрагивает целое отношение, а не только один столбец
  • Я не использую множественное наследование.

Где я должен искать, чтобы найти основную проблему?

Я пытаюсь настроить таблицы для нового проекта django (то есть таблицы НЕ уже существуют в базе данных); версия django — 1.7, а конец db — PostgreSQL. Название проекта красное. Результаты попытки миграции:

python manage.py makemigrations crud

Migrations for 'crud':
  0001_initial.py:
    - Create model AddressPoint
    - Create model CrudPermission
    - Create model CrudUser
    - Create model LDAPGroup
    - Create model LogEntry
    - Add field ldap_groups to cruduser
    - Alter unique_together for crudpermission (1 constraint(s))

python manage.py migrate crud

Operations to perform:
  Apply all migrations: crud
Running migrations:
  Applying crud.0001_initial...Traceback (most recent call last):
  File "manage.py", line 18, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
    self.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 82, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "crud_crudpermission" already exists

Некоторые основные моменты из файла миграции:

dependencies = [
    ('auth', '0001_initial'),
    ('contenttypes', '0001_initial'),
]
    migrations.CreateModel(
        name='CrudPermission',
        fields=[
            ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
            ('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
            ('_created', models.DateTimeField(null=True, editable=False, blank=True)),
            ('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
            ('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
            ('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
            ('can_add', models.BooleanField(default=False, verbose_name=b'add')),
            ('can_change', models.BooleanField(default=False, verbose_name=b'change')),
            ('restrict_change_to_own', models.BooleanField(default=False)),
            ('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
            ('restrict_delete_to_own', models.BooleanField(default=False)),
            ('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
        ],
        options={
            'verbose_name': 'CRUD permission',
        },
        bases=(models.Model,),
    ),
    migrations.AlterUniqueTogether(
        name='crudpermission',
        unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
    )

Приложение crud не предназначено, чтобы на самом деле ничего делать, но я использую его в другом приложении, поэтому, когда я пытаюсь выполнить миграцию из этого приложения, я запускаю вышеупомянутую проблему.

Я нашел другие примеры в Интернете людей с подобными проблемами, но ни один из их случаев не применяется, потому что

  • Проблема затрагивает целое отношение, а не только один столбец
  • Я не использую множественное наследование.

Где я должен искать, чтобы найти основную проблему?

4b9b3361

Ответ 1

Это работает довольно хорошо

./manage.py migrate --fake default

Источник: — https://github.com/nijel/weblate/issues/587

Ответ 2

Сделайте ли python manage.py migrate --fake.

Прочитайте https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-migrate.

Ответ 3

У вас возникла аналогичная проблема, в конечном итоге удаленные все .py файлы в папке миграции (django 1.7 создает один автоматически), после этого отлично сработал.

Ответ 4

Я столкнулся с подобной проблемой, когда добавил пару новых полей в существующую модель. Я использую Django 1.9, который представил --run-syncdb. Запуск manage.py migrate --run-syncdb исправил мои таблицы.

Ответ 5

Я столкнулся с аналогичными проблемами, когда я изменил имя столбца. Я получал ту же ошибку, что упоминался в трассировке стека, заданной с его вопросом.

Вот что я сделал.

Сначала я запускал поддельные миграции. Затем я удалил запись (миграции, которую я хотел запустить) из таблицы django_migrations и снова выполнил миграцию (на этот раз не подделка).

Изменения появились как ожидалось для меня.

надеюсь, что это будет полезно.

Ответ 6

Теперь (я использую Django 1.9) вы можете сделать:

./manage.py [—database DATABASE] —fake [app_label] [имя_переменной]

Таким образом, вы ориентируетесь на проблему с большей точностью, и вы можете подделать только проблемную миграцию в конкретной базе данных.

Итак, глядя на вопрос, вы могли:

./manage.py —database default —fake crud crud.0001_initial

Ответ 7

Django предоставляет --fake-initial которую я нашел эффективной для моего использования. Из миграционной документации Django:

—fake-начальная

Позволяет Django пропускать начальную миграцию приложений, если все таблицы базы данных с именами всех моделей, созданных всеми операциями CreateModel в этой миграции, уже существуют. Этот параметр предназначен для использования при первом запуске миграций для базы данных, в которой ранее использовались миграции. Однако этот параметр не проверяет соответствие схемы базы данных за пределами совпадающих имен таблиц, поэтому его можно использовать только в том случае, если вы уверены, что ваша существующая схема совпадает с записанной при первоначальной миграции.

Для моего использования я только что вытащил проект из системы управления версиями и готовился добавить несколько новых полей модели. Я добавил поля, запустил ./manage.py makemigrations и затем попытался запустить ./manage.py migrate что ./manage.py migrate ошибку, поскольку, как и следовало ожидать, многие поля уже существовали в существующей базе данных.

То, что я должен был сделать, — это запустить makemigrations сразу после makemigrations проекта из управления версиями, чтобы создать снимок состояния существующих моделей. Затем следующим шагом будет запуск ./manage.py migrate --fake-initial.

После этого вы можете добавить и makemigrations migrate > migrate как обычно.

ПРИМЕЧАНИЕ: я не знаю, пропустит ли --fake-initial существующие поля и добавит ли новые. Я решил закомментировать новые поля, которые я создал до этого момента, запустить --fake-initial как будто это было первое, что я сделал после извлечения из системы управления версиями, а затем добавил в обновленные поля в следующей миграции.

Другая связанная с этим документация: https://docs.djangoproject.com/en/dev/topics/migrations/#initial-migrations

Ответ 8

Я нашел и решил конкретный пример этой ошибки в проекте Django 1.10, когда я менял поле внешнего ключа с именем member, чтобы указать на другую таблицу. Я менял это в трех разных моделях, и я ударил эту ошибку на всех из них. В моей первой попытке я переименовал member в member_user и попытался создать новое поле member в качестве внешнего ключа, указывающего на новую таблицу, но это не сработало.

Я обнаружил, что когда я переименовал столбец member, он не изменил имя индекса в форме <app>_<model>_<hash>, и когда я попытался создать новый столбец member, он попытался создать такое же имя индекса, хэш-часть имени была одинаковой.

Я решил проблему, создав новое отношение member_user временно и скопировав данные. Это создало новый индекс с другим хэшем. Затем я удалил member и воссоздал его, указав на новую таблицу, и с этим будущим конфликтующим именем индекса. Как только это было сделано, я выполнил шаг RunPython, чтобы заполнить новый столбец member ссылкой на соответствующую таблицу. Я закончил, добавив миграции RemoveField, чтобы очистить временные столбцы member_user.

Мне пришлось разделить мои миграции на два файла, потому что я получил эту ошибку:

psycopg2.OperationalError: не может ALTER TABLE «<table_name > » потому что он имеет ожидающие события запуска

После создания и копирования данных в member_user мне не удалось удалить member в той же транзакции миграции. Это может быть специфическим ограничением postgres, но его легко решить, создав еще одну транзакцию и перемещая все после создания и копирования member_user во вторую миграцию.

Ответ 9

Я нашел эту проблему в web2pyframework в models/config.py.

+ Изменить

settings.base.migrate = True

в конфигурационном файле

settings.base.migrate = False

Задача решена.

Понравилась статья? Поделить с друзьями:
  • Ошибка отношение не существует позиция 15
  • Ошибка отношение не существует sql состояние 42p01
  • Ошибка отношение не существует postgresql hibernate
  • Ошибка отправки налоговой декларации в личном кабинете
  • Ошибка отправки на сервер фсс