pythondjangodjango-3.2

Table not found in migration file


Error Message

django.db.utils.OperationalError: no such table: clientauth_tbltokentypes

What I am trying to do

I am trying to migrate data with table generation.

models.py

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

I ran the command python manage.py makemigrations, which created the file 0001_initial.py.

Then in the migration file, I added managers:

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()
            ]
        )
    ]

Am I missing anything?


Solution

  • Wrap your function call in migrations.RunPython, otherwise it will be run while assigning operations, before the migration can even be run to create your table.

    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
        ]
    

    Also note, from https://docs.djangoproject.com/en/3.2/topics/migrations/#data-migrations:

    [Data migrations are] best written as separate migrations, sitting alongside your schema migrations.

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