[Answered ]-Undefined Classes in Django 1.7 Migrations

2đź‘Ť

âś…

In your migration you should access the historical models instead of importing the actual models as you usually do.

This is done to nto fall in the issue you have. To get the historical mdoels (i.e. a model which existed when you created such migration) you have to replace your code:

Check this from the official django docs (this case is for data migrations althought the concept applies to your case):

# -*- coding: utf-8 -*-
from django.db import models, migrations

def combine_names(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.
    Person = apps.get_model("yourappname", "Person")
    for person in Person.objects.all():
        person.name = "%s %s" % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]

This migration does a python code, and needs a certain model. To avoid importing models which are not existent anymore, it does not a direct import, but an “aggregated” access to the model in “that exact time slice”. This code:

apps.get_model("yourappname", "Person")

would be an exact replacement of:

from yourappname.models import Person

since the latter would fail in a brand-new installation which has to run the migrations.

Edit please post the full code of your migration to see if I can help you with your particular case, since I have a project with models that aren’t anymore (i.e. deleted) but have no such issue.

👤Luis Masuelli

Leave a comment