问题
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
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
EDIT: 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
Settings:
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/'
models:
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']
回答1:
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
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.
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())
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.
来源:https://stackoverflow.com/questions/32383978/no-such-column-error-in-django-models