【问题标题】:No such column error in Django modelsDjango 模型中没有这样的列错误
【发布时间】:2015-11-29 18:44:56
【问题描述】:

我正在向我的 Django 模型添加一个新字段,但无论新字段是什么,当我尝试运行 makemigrations 时都会收到 no such column 错误

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”。

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

编辑:这里有一些其他的东西

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'] 

【问题讨论】:

  • 请提供完整的堆栈跟踪,在这里几乎不可能为您提供帮助。还提供一些设置,其他模型文件等。
  • 我编辑了问题以包括模型、设置和完整的堆栈跟踪

标签: python django django-models django-migrations


【解决方案1】:

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

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 = 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) )          

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

这里的解决方案是去掉forms.MultipleChoiceFieldCONTROL_CHOICES,使用ModelMultipleChoiceField。 它是专门为这种情况设计的:

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

由于查询集是惰性求值的,因此在显示表单时,您将直接从数据库中获取最新的对象。 Django 还将为您处理验证和一切。

【讨论】:

  • 很高兴它有帮助 :) 请将答案标记为已接受,它可能对面临相同问题的其他用户有用。
猜你喜欢
  • 2020-04-07
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2017-12-10
  • 2011-05-06
  • 2017-03-27
相关资源
最近更新 更多