首页 > 解决方案 > 在迁移文件中找不到表

问题描述

错误信息

django.db.utils.OperationalError:没有这样的表:clientauth_tbltokentypes

我想要做什么

我正在尝试使用表生成迁移数据。

模型.py

class tbltokentypes(models.Model):
    token_type_id: AutoField(primary_key=True)
    token_type: CharField(max_length=30)

我运行了python manage.py makemigrations创建文件 0001_initial.py 的命令。

然后在迁移文件中,我添加了管理器:

from django.db import migrations, models
from clientauth.models import tbltokentypes

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='tbltokentypes',
            fields=[
                ('token_type_id', models.AutoField(primary_key=True, serialize=False, verbose_name='token_type_id')),
                ('token_type', models.CharField(max_length=30)),
            ],
            managers=[
                tbltokentypes(token_type = "Registration").save()
            ]
        )
    ]

我错过了什么吗?

标签: pythondjangodjango-3.2

解决方案


将您的函数调用包装在 中migrations.RunPython,否则它将在分配operations时运行,甚至可以在运行迁移以创建您的表之前运行。

from django.db import migrations, models
# from clientauth.models import tbltokentypes  # Remove this


# Add this function
def migrate_tbltokentypes(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    tbltokentypes = apps.get_model('clientauth', 'tbltokentypes')
    tbltokentypes(token_type="Registration").save()


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='tbltokentypes',
            fields=[
                ('token_type_id', models.AutoField(primary_key=True, serialize=False)),
                ('token_type', models.CharField(max_length=30)),
            ],
            # managers=[                                             # Change this
            #     tbltokentypes(token_type = "Registration").save()  #
            # ]                                                      #
        ),
        migrations.RunPython(migrate_tbltokentypes),                 # to this
    ]

另请注意,来自https://docs.djangoproject.com/en/3.2/topics/migrations/#data-migrations

[数据迁移] 最好写成单独的迁移,与您的架构迁移并排。

python manage.py makemigrations --empty clientauth --name migrate_tbltokentypes

推荐阅读