2014-09-24 69 views
1

我遇到了旧迁移包含对不再定义的类甚至模块的引用的问题。我解决这些问题的最佳方式是什么?Django中的未定义类1.7迁移

我可以通过删除这些引用来摆脱错误消息,但是如果我打破迁移?

我也是唯一一个认为Django 1.7 migrations实际上导入了我的代码库部分代码的人有点疯狂,因为我显然会编辑它?

例错误消息:

Traceback (most recent call last): 
    ... 
    File "/.../migrations/0001_initial.py", line 194, in Migration 
bases=(model_utils.models.UserPersonMixin, models.Model), 
AttributeError: 'module' object has no attribute 'UserPersonMixin' 

在这种情况下,UserPersonMixin是一个抽象基类,使用该模型来从继承但同时重组我最近丢弃。

回答

2

在您的迁移中,您应该访问历史模型,而不是像往常一样导入实际模型。

这样做是为了解决您的问题。为了让历史mdoels(即当你创造了这样的迁移所存在的模型),你必须更换代码:

检查这个来自官方Django文档(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), 
    ] 

这个迁移做了python代码,并需要一定的模型。为了避免导入不再存在的模型,它不是直接导入,而是在“精确时间片”中对模型进行“聚合”访问。此代码:

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

将是一个确切的更换:

from yourappname.models import Person 

,因为后者在一个全新的安装具有运行迁移会失败。

编辑请发表您的迁移的完整代码,看看我是否能帮助你与你的具体情况,因为我有一个模型,是不再项目(即删除),但有没有这样的问题。

+0

在我的情况下,在我摆脱模型之前创建了有关的迁移,所以这可能是我遇到问题的原因。尽管我喜欢你的解决方案。在发布这个问题之前,我正在浏览文档,但很难找到它,所以感谢分享! – azulu 2014-09-28 21:39:13