我正在为我的Django模型添加一个新字段,但无论新字段是什么,我在尝试运行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”调用,如上所述。
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']
答案 0 :(得分:3)
这里的问题是您在模型仍在加载且应用程序未完全初始化时查询数据库:
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.MultipleChoiceField
和CONTROL_CHOICES
并使用ModelMultipleChoiceField
。
它专为此案例设计:
class CompareForm(forms.Form):
select = forms.ModelMultipleChoiceField(queryset=Control.objects.all())
由于对查询集进行了延迟评估,因此在显示表单时,您将直接从数据库中获取对象。 Django还将为您处理验证和一切。