Django 3.2 — django.db.utils.Ошибка программирования: столбец «идентификатор», на который ссылается ограничение внешнего ключа, не существует

#python #django #postgresql #django-database #django-postgresql

Вопрос:

В настоящее время я разрабатываю проект django, и мне нужно было перейти на базы данных PostgreSQL. Я сделал это точно так же, как это было в моем settings.py файл:

 DATABASES = {
    'default': {
        'ENGINE'  : 'django.db.backends.postgresql_psycopg2',
        'NAME'    : 'lifeplaner',
        'USER'    : 'postgres',
        'PASSWORD': <my_password>,
        'HOST'    : 'localhost',
        'PORT'    : '5432',
    }
}
 

Я удалил все свои каталоги миграции и запустил python manage.py makemigrations и python manage.py migrate , но я получаю эту ошибку (которая не возникала, когда я использовал sqlite3):

 (life-planer-app-env) C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerAppLifePlaner>python manage.py migrate
Operations to perform:
  Apply all migrations: Calendar, Manager, ToDoList, admin, auth, contenttypes, django_celery_beat, django_celery_results, sessions
Running migrations:
  Applying ToDoList.0001_initial...Traceback (most recent call last):
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "id" referenced in foreign key constraint does not exist


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

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagement__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagement__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagementbase.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagementbase.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagementbase.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangocoremanagementcommandsmigrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbmigrationsexecutor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbmigrationsexecutor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbmigrationsexecutor.py", line 230, in apply_migration
    migration_recorded = True
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsbaseschema.py", line 118, in __exit__
    self.execute(sql)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsbaseschema.py", line 145, in execute
    cursor.execute(sql, params)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbutils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:UsersuserDesktopProgrammation-PythonProjetsApplicationsLifePlanerApplife-planer-app-envlibsite-packagesdjangodbbackendsutils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist
 

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

 # Generated by Django 3.2.6 on 2021-09-20 15:52

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='DailyTaskReview',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('total_tasks', models.PositiveIntegerField()),
                ('reached', models.PositiveIntegerField()),
                ('unreached', models.PositiveIntegerField()),
                ('success_rate', models.FloatField()),
                ('failure_rate', models.FloatField()),
                ('reached_before_reminder', models.PositiveIntegerField()),
                ('reached_after_reminder', models.PositiveIntegerField()),
                ('date', models.DateField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='MonthlyTaskReview',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('total_tasks', models.PositiveIntegerField()),
                ('reached', models.PositiveIntegerField()),
                ('unreached', models.PositiveIntegerField()),
                ('success_rate', models.FloatField()),
                ('failure_rate', models.FloatField()),
                ('reached_before_reminder', models.PositiveIntegerField()),
                ('reached_after_reminder', models.PositiveIntegerField()),
                ('date', models.IntegerField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='WeeklyTaskReview',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('total_tasks', models.PositiveIntegerField()),
                ('reached', models.PositiveIntegerField()),
                ('unreached', models.PositiveIntegerField()),
                ('success_rate', models.FloatField()),
                ('failure_rate', models.FloatField()),
                ('reached_before_reminder', models.PositiveIntegerField()),
                ('reached_after_reminder', models.PositiveIntegerField()),
                ('date', models.IntegerField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='WeeklyTask',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=20, unique=True)),
                ('description', models.TextField(null=True)),
                ('type_of_task', models.CharField(choices=[('sport', 'Sport'), ('studies', 'Studies'), ('some_chores', 'Home chores'), ('selfcare', 'Selfcare'), ('new_habits', 'New habits'), ('new_skills', 'New skills')], max_length=20)),
                ('active', models.BooleanField(default=True)),
                ('reminder', models.DateTimeField(null=True)),
                ('send_reminder', models.BooleanField(default=False)),
                ('reminder_sent', models.BooleanField(default=False)),
                ('finished_before_reminder', models.BooleanField(default=None, null=True)),
                ('date', models.IntegerField()),
                ('time_finish', models.DateTimeField(default=None, null=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TypeOfWeeklyTaskRate',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('number_newskills', models.PositiveIntegerField()),
                ('number_newhabits', models.PositiveIntegerField()),
                ('number_selfcare', models.PositiveIntegerField()),
                ('number_chores', models.PositiveIntegerField()),
                ('number_studies', models.PositiveIntegerField()),
                ('number_sport', models.PositiveIntegerField()),
                ('number_nonreferenced', models.PositiveIntegerField()),
                ('review', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ToDoList.weeklytaskreview')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TypeOfMonthlyTaskRate',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('number_newskills', models.PositiveIntegerField()),
                ('number_newhabits', models.PositiveIntegerField()),
                ('number_selfcare', models.PositiveIntegerField()),
                ('number_chores', models.PositiveIntegerField()),
                ('number_studies', models.PositiveIntegerField()),
                ('number_sport', models.PositiveIntegerField()),
                ('number_nonreferenced', models.PositiveIntegerField()),
                ('review', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ToDoList.monthlytaskreview')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TypeOfDailyTaskRate',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('number_newskills', models.PositiveIntegerField()),
                ('number_newhabits', models.PositiveIntegerField()),
                ('number_selfcare', models.PositiveIntegerField()),
                ('number_chores', models.PositiveIntegerField()),
                ('number_studies', models.PositiveIntegerField()),
                ('number_sport', models.PositiveIntegerField()),
                ('number_nonreferenced', models.PositiveIntegerField()),
                ('review', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ToDoList.dailytaskreview')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='MonthlyTask',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=20, unique=True)),
                ('description', models.TextField(null=True)),
                ('type_of_task', models.CharField(choices=[('sport', 'Sport'), ('studies', 'Studies'), ('some_chores', 'Home chores'), ('selfcare', 'Selfcare'), ('new_habits', 'New habits'), ('new_skills', 'New skills')], max_length=20)),
                ('active', models.BooleanField(default=True)),
                ('reminder', models.DateTimeField(null=True)),
                ('send_reminder', models.BooleanField(default=False)),
                ('reminder_sent', models.BooleanField(default=False)),
                ('finished_before_reminder', models.BooleanField(default=None, null=True)),
                ('date', models.IntegerField()),
                ('time_finish', models.DateTimeField(default=None, null=True)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='DailyTask',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=20, unique=True)),
                ('description', models.TextField(null=True)),
                ('type_of_task', models.CharField(choices=[('sport', 'Sport'), ('studies', 'Studies'), ('some_chores', 'Home chores'), ('selfcare', 'Selfcare'), ('new_habits', 'New habits'), ('new_skills', 'New skills')], max_length=20)),
                ('active', models.BooleanField(default=True)),
                ('reminder', models.DateTimeField(null=True)),
                ('send_reminder', models.BooleanField(default=False)),
                ('reminder_sent', models.BooleanField(default=False)),
                ('time_finish', models.DateTimeField(default=None, null=True)),
                ('finished_before_reminder', models.BooleanField(default=None, null=True)),
                ('date', models.DateField()),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
    ]
 

А вот вывод команды d в оболочке sql, если это может помочь:

  SchÚma |                Nom                |   Type   | PropriÚtaire
-------- ----------------------------------- ---------- --------------
 public | Calendar_event                    | table    | postgres
 public | Calendar_event_id_seq             | sÚquence | postgres
 public | Manager_theuser                   | table    | postgres
 public | auth_group                        | table    | postgres
 public | auth_group_id_seq                 | sÚquence | postgres
 public | auth_group_permissions            | table    | postgres
 public | auth_group_permissions_id_seq     | sÚquence | postgres
 public | auth_permission                   | table    | postgres
 public | auth_permission_id_seq            | sÚquence | postgres
 public | auth_user                         | table    | postgres
 public | auth_user_groups                  | table    | postgres
 public | auth_user_groups_id_seq           | sÚquence | postgres
 public | auth_user_id_seq                  | sÚquence | postgres
 public | auth_user_user_permissions        | table    | postgres
 public | auth_user_user_permissions_id_seq | sÚquence | postgres
 public | django_content_type               | table    | postgres
 public | django_content_type_id_seq        | sÚquence | postgres
 public | django_migrations                 | table    | postgres
 public | django_migrations_id_seq          | sÚquence | postgres
 

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

Комментарии:

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

2. Ой, извините, я не подумал об удалении всей базы данных. Я чувствую себя довольно глупо, тратя на это так много времени. Я последовал инструкциям, которые вы мне дали, в том же порядке, и это сработало. Большое вам спасибо !