Django模型中没有这样的列错误 [英] No such column error in Django models

查看:84
本文介绍了Django模型中没有这样的列错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django模型中添加了一个新字段,但是无论新字段是什么,当我尝试运行makemigrations时都不会出现此类错误

I'm adding a new field to my Django model, but no matter what the new field is, I get a no such column error when I try to run makemigrations

File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
  return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: stats_control.con_LD_file

这是我的模型代码现在的样子。如果已注释的字段未注释,则它将失败上述的 makemigrations调用。

Here's what my code for the model looks like now. If the commented field is uncommented, it will fail the "makemigrations" call like above.

class Control(models.Model):
    submissions = models.ManyToManyField(Submission, blank=True)
    con_name = models.CharField('name', max_length=200)
    con_bed_file = models.FileField('.bed file', upload_to='controls')
    con_bim_file = models.FileField('.bim file', upload_to='controls')
    con_fam_file = models.FileField('.fam file', upload_to='controls')
    con_SNPs = models.IntegerField('# of SNPs', default = 0, blank=True, null=True)
    #con_LD_file = models.FileField('LD score file', upload_to='LD_scores', blank=True, null=True)
    def __unicode__(self):              # __unicode__ on Python 2
        return self.con_name

编辑:这还有其他一些事情

here are some other things

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/Applications/Canopy.app/appdata/canopy-1.5.4.3105.macosx-x86_64/Canopy.app/Contents/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/hugokitano/Documents/Summer_Code/statread/stats/models.py", line 39, in <module>
    class CompareForm(forms.Form):
  File "/Users/hugokitano/Documents/Summer_Code/statread/stats/models.py", line 40, in CompareForm
    select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__
    self._fetch_all()
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/hugokitano/canopy/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: stats_control.con_LD_file

设置:

Django settings for statread project.

Generated by 'django-admin startproject' using Django 1.8.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'igl9^f%j_3&2kk)iuo8lofz%3zzs$v!j+(-#tgl!^==il)k^yo'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'stats',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'statread.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'statread.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Los_Angeles'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

MEDIA_ROOT = '/Users/hugokitano/Documents/Summer_Code/storage'
MEDIA_URL = 'http://127.0.0.1:8000/stats/media/'

模型:

from django.db import models
from django import forms
from django.forms import ModelForm
from django.utils import timezone
from picklefield.fields import PickledObjectField
#from django.contrib.auth.models import User

class Submission(models.Model):
    sub_name = models.CharField(max_length=200)
    sub_file = models.FileField(upload_to='statistics')
    sub_date = models.DateTimeField('date submitted', blank=True, null=True, default=timezone.now)
    def __unicode__(self):              # __unicode__ on Python 2
        return self.sub_name

class Output(models.Model):
    submission = models.OneToOneField(Submission)
    data = PickledObjectField()
    outputFile = models.FileField('Output file', upload_to='outputs', blank = True, null = True)
    numSNPs = models.IntegerField(default=0)

class Control(models.Model):
    submissions = models.ManyToManyField(Submission, blank=True)
    con_name = models.CharField('name', max_length=200)
    con_bed_file = models.FileField('.bed file', upload_to='controls')
    con_bim_file = models.FileField('.bim file', upload_to='controls')
    con_fam_file = models.FileField('.fam file', upload_to='controls')
    con_SNPs = models.IntegerField('# of SNPs', default = 0, blank=True, null=True)
    con_LD_file = models.FileField('LD score file', upload_to='LD_scores', blank=True, null=True)
    def __unicode__(self):              # __unicode__ on Python 2
        return self.con_name

class SubmissionForm(ModelForm):
    class Meta:
        model = Submission
        fields = ['sub_name', 'sub_file'] 

CONTROL_CHOICES = Control.objects.all()

class CompareForm(forms.Form):
    select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          

class ControlForm(ModelForm):
    class Meta:
        model = Control
        fields = ['con_name', 'con_bed_file', 'con_bim_file', 'con_fam_file'] 


推荐答案

这里的问题是当模型仍在加载且应用未完全初始化时,您正在查询数据库:

The problem here is you're querying the database while models are still loading and apps are not fully initialized:

File "/Users/hugokitano/Documents/Summer_Code/statread/stats/models.py", line 40, in CompareForm
select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          

CONTROL_CHOICES 是先前在文件中定义的查询集:

CONTROL_CHOICES is a queryset defined earlier in your file:

CONTROL_CHOICES = Control.objects.all()

为简单起见,请永远不要这样做。如果在未完全加载应用程序的情况下查询数据库,则所有内容都会崩溃。

To keep it simple, never, never do this. If you query the database while your apps are not fully loaded, everything will crash.

此外,您的代码也将无法正常运行:

Also, your code will not behave as expected:

class CompareForm(forms.Form):
    select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          

因为您直接在查询集中迭代您的表单定义中,您将获得一个静态元素列表,这些元素在您重新启动服务器之前不会改变(即使您在数据库中添加了新元素)。

Since you are iterating on the queryset directly in your form definition, you will get a static list of elements that will never change (even if you add new ones in database) until you restart your server.

此处的解决方案是摆脱 forms.MultipleChoiceField CONTROL_CHOICES 并使用 ModelMultipleChoiceField
专门针对这种情况设计:

The solution Here is to get rid of forms.MultipleChoiceField and CONTROL_CHOICES and use ModelMultipleChoiceField. It is designed specifically for this case:

class CompareForm(forms.Form):
    select = forms.ModelMultipleChoiceField(queryset=Control.objects.all())

由于对查询集的计算是惰性的,显示表单时,您将直接从数据库获取最新的对象。
Django还将为您处理验证和所有操作。

As the queryset is lazily evaluated, you'll get up-to-dase objects straight from the database when displaying the form. Django will also handle validation and everything for you.

这篇关于Django模型中没有这样的列错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆