运行显式创建表的迁移时未创建Django表。

时间:2016-08-31 16:38:49

标签: mysql django database django-migrations

在尝试对我的Django模型进行一些重大更改时,我严重搞砸了所有内容。幸运的是,我没有进行任何更改,因此我放弃了所有更改。下一步是让我的数据库恢复原样。最终,我达到了可以成功运行makemigrationsmigrate命令的程度。但是,每当我尝试访问该网站时,我都会ProgrammingError说我的表topspots_notification不存在。

我的migrations文件夹中有以下迁移文件:

# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-25 15:52
from __future__ import unicode_literals

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


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('topspots', '0018_siteuser_share_location'),
    ]

    operations = [
        migrations.CreateModel(
            name='Notification',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('message', models.TextField()),
                ('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipient_notification', to=settings.AUTH_USER_MODEL)),
                ('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sender_notification', to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]

应该创建该表。如果我尝试专门运行此迁移,则在尝试取消应用引用该表的后续迁移时会失败,因为该表不存在。我已经尝试删除上面的迁移(创建了我的notification表),以及之后的每个模型。然后我再次运行makemigrationsmigrate,但它说没有要应用的迁移,我的表仍未创建。

我的问题是:为什么在运行迁移时我的表格不会被创建?我知道我可以在MySQL中手动创建表格,但我想知道我做错了什么以这种方式弄乱我的数据库。

我已经看到了一些与未创建表格和未应用迁移相关的SO帖子,但我还没有发现任何对我有用的内容。

  • 我的桌子不是“非托管”桌子。
  • 我尝试删除所有迁移并生成新迁移。
  • 我尝试为整个项目运行migrate,并为特定应用甚至特定迁移运行迁移

我的假设是我的数据库本身有一些东西告诉Django不应用迁移,但我不知道该寻找什么。

任何建议将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

When you succesfully run a migration, django stores a log of that migration in the django_migrations table (you can check it directly in your database) so the next time you try to run the same migration, django will see in the logs that you already run it once and it wont try to create the table again.

You could try to clean the applied migrations by modifying that table and then run the migrations again OR [recommended] go back to a safe point by using --fake:

let's say that you had problems with migration 0003 and 0002 but migration 0001 was ok... so to go back to migration 0001 do

./manage.py migrate my_app 0001 --fake

it will remove the 0002 and 0003 migrations on the django_migrations table and you'll be able to recreate them or run the new migrations again

Please do a backup of your database before testing this :P don't want to be responsible for any data loss XD

Hope this helps