Programing

django.db.utils.ProgrammingError : 관계가 이미 있습니다.

lottogame 2020. 12. 8. 07:37
반응형

django.db.utils.ProgrammingError : 관계가 이미 있습니다.


새 django 프로젝트를위한 테이블을 설정하려고합니다 (즉, 테이블이 데이터베이스에 이미 존재하지 않습니다). django 버전은 1.7이고 db 백엔드는 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))

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 앱은 실제로 아무것도 할 수 없지만 다른 앱을 사용하므로 해당 앱에서 마이그레이션을 시도하면 위의 문제가 발생합니다.

비슷한 문제를 가진 사람들의 웹에서 다른 예를 찾았지만 해당 사례가 적용되지 않는 것 같습니다.

  1. 문제는 하나의 열이 아닌 전체 관계에 영향을 미칩니다.
  2. 다중 상속을 사용하지 않습니다.

근본적인 문제를 찾으려면 다음에 어디를 찾아야합니까?


이것은 꽤 잘 작동합니다

./manage.py migrate --fake default

출처 :-https: //github.com/nijel/weblate/issues/587


Do python manage.py migrate --fake initally.

Read https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-migrate


Been facing a similar issue, eventually deleted all .py files in migration folder (django 1.7 creates one automatically), worked perfectly after that.


I've faced similar issue when added couple new fields to existing model. I'm using Django 1.9, which introduced --run-syncdb option. Running manage.py migrate --run-syncdb fixed my tables.


I was facing the similar issues, where i had changed column name. I was getting same error as mentioned in the stack-trace provided with he question.

Here's what I did.

I ran fake migrations first. Then i removed it's(migrations i wanted to run) entry from django_migrations table and ran migrations again(no fake this time).

Changes appeared as expected for me.

hope this is helpful.


Now (I'm using Django 1.9) you can make:

./manage.py [--database DATABASE] --fake [app_label] [migration_name]

This way you're targeting the problem with more accuracy, and you can fake only the problematic migration on the specific database.

So, looking at the question, you could:

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


Django provides a --fake-initial option which I found effective for my use. From the Django Migration Documentation:

--fake-initial

Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations against a database that preexisted the use of migrations. This option does not, however, check for matching database schema beyond matching table names and so is only safe to use if you are confident that your existing schema matches what is recorded in your initial migration.

For my use, I had just pulled a project from version control and was preparing to add some new model fields. I added the fields, ran ./manage.py makemigrations and then attempted to run ./manage.py migrate which threw the error since, as one would expect, many of the fields already existed in the existing database.

What I should have done was to run makemigrations immediately after pulling the project from versions control to create a snapshot of existing models' state. Then, running the ./manage.py migrate --fake-initial would be the next step.

After that you can add away and makemigrations > migrate as normal.

NOTE: I do not know if a --fake-initial would skip existing fields and add new ones. I opted to comment out the new fields I'd created up to that point, run the --fake-initial as if it were the first thing I did after pulling from version control, then added in updated fields in the next migration.

Other related documentation: https://docs.djangoproject.com/en/dev/topics/migrations/#initial-migrations


I found and solved a particular example of this error in a Django 1.10 project while I was changing a foreign key field named member to point to a different table. I was changing this in three different models and I hit this error on all of them. In my first attempt I renamed member to member_user and tried to create a new field member as a foreign key pointing at the new table, but this didn't work.

What I found is that when I renamed the member column it did not modify the index name in the form <app>_<model>_<hash> and when I tried to create a new member column it tried to create the same index name because the hash portion of the name was the same.

I resolved the problem by creating a new member_user relation temporarily and copying the data. This created a new index with a different hash. I then deleted member and recreated it pointing at the new table and with it the would-be conflicting index name. Once that was done I ran the RunPython step to populate the new member column with references to the applicable table. I finished by adding RemoveField migrations to clean up the temporary member_user columns.

I did have to split my migrations into two files because I received this error:

psycopg2.OperationalError: cannot ALTER TABLE "<table_name>" because it has pending trigger events

After the creation and copy of data into member_user I was not able to remove member in the same migration transaction. This may be a postgres specific limitation, but it was easily resolved by creating another transaction and moving everything after creating and copying member_user into the second migration.


I found this problem in web2pyframework in models/config.py .

Change

settings.base.migrate = True

on config file to

settings.base.migrate = False

Problem solved.

참고URL : https://stackoverflow.com/questions/29830928/django-db-utils-programmingerror-relation-already-exists

반응형