2014-09-24 115 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