2016-02-12 114 views
0

使用Django 1.8.2,我試圖在一個模型上進行遷移。Django遷移,MyModel.objects.get()返回空列表

下面是模型的爲例:

class Question(models.Model): 
    module = models.ForeignKey(Module) 
    my_order = models.PositiveIntegerField(default=0, blank=False, null=False) 
    question = models.CharField(max_length=400) 

這裏是遷移:

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals 

from django.db import models, migrations 

def save_answer(apps, schema_editor): 
    question_model = apps.get_model("modules", "question") 
    print question_model 
    question_list = question_model.objects.all() 
    print question_list 
    for question in question_list: 
     #some changes here 
     question.save() 

class Migration(migrations.Migration): 

    dependencies = [ 
     ('modules', '0002_auto_20160212_1940'), 
    ] 

    operations = [ 
     migrations.RunPython(save_answer), 
    ] 

我已經在此基礎上創建的文檔這樣的:https://docs.djangoproject.com/fr/1.8/topics/migrations/#data-migrations

我的問題是即使數據庫中存在Question對象,question_list始終爲空。 但是,打印question_model工作正常,所以我想我有合適的模型。 然後我不明白爲什麼我不能得到相應的對象。

任何幫助將是感激,

感謝,

澤維爾

編輯: 其實,我發現我的問題可能不是遷移本身,因爲當我使用python manage.py migrate每件事情都可以正常工作,但是當我使用我的makefile重新創建數據庫時,會發生錯誤。 這裏是Makefile中:

reinit-database: 
    psql -c "DROP DATABASE myDataBase" || true 
    psql -c "CREATE DATABASE myDataBase" 
    find . -type d -name "migrations" 
    find . -type f -name "*.pyc" -delete 
    python manage.py reset_db 
    python manage.py migrate auth || true 
    python manage.py migrate 
    make load-fixtures 
    python manage.py createsuperuser 

然後,我真的不明白它是什麼不工作的原因,但現在我知道了一招......

無論如何,如果有人知道發生了什麼, 我很感興趣 !

Xavier

回答

0

你的代碼看起來不錯。唯一的問題是你正在打印qcm_list。那是什麼?

+0

我的意思是question_list,我在創建帖子時發生了錯誤,但是我的代碼在該點上是正確的。 –

+0

我不明白你想做什麼。爲什麼在遷移後放棄數據庫? –

+0

你是完全正確的,我的錯誤來自Makefile,實際上是使load-fixtures = python manage.py loaddata data_dump.json。 顯然,之前沒有數據,這就是爲什麼我得到一個空列表... 然後,我需要更正生成文件,並在data_dump上工作! 感謝您的幫助。 –