Django 模型中没有此类列错误

2024-02-28

我正在向 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/'

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

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

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 and CONTROL_CHOICES并使用ModelMultipleChoiceField https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelmultiplechoicefield。 它是专门针对这种情况设计的:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django 模型中没有此类列错误 的相关文章

  • 如何替换Python字符串中的正确字母

    任务是 您的任务是纠正数字化文本中的错误 您只需处理以下错误 S 被误解为 5 O 被误解为 0 I 被误解为 1 我的代码 def correct string for i in string if 5 in string string
  • DynamodB:如何更新排序键?

    该表有两个键 filename 分区键 和eventTime 排序键 我要更新eventTime对于某些filename Tried put item and update item 发送相同的filename与新的eventTime但这些
  • 如何在 Pandas Python 中按 id 对行进行排名

    我有一个像这样的数据框 id points1 points2 1 44 53 1 76 34 1 63 66 2 23 34 2 44 56 我想要这样的输出 id points1 points2 points1 rank points2
  • pyCUDA无法打印结果

    最近 我使用 pip 为我的 python3 4 3 安装 pyCUDA 但我在测试示例代码时发现 https documen tician de pycuda tutorial html getting started https doc
  • Python:json_normalize pandas 系列给出 TypeError

    我在 pandas 系列中有数万行像这样的 json 片段df json IDs lotId 1 Id 123456 date 2009 04 17 bidsCount 2 IDs lotId 2 Id 123456 date 2009 0
  • 使用 Python 和 lmfit 拟合复杂模型?

    我想适合椭偏仪 http en wikipedia org wiki Ellipsometry使用 LMFit 将数据转换为复杂模型 两个测量参数 psi and delta 是复杂函数中的变量rho 我可以尝试将问题分离为实部和虚部共享参
  • Python speedtest.net,或等效的[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 是否有一个 Python 库可以实现 SpeedTest net 测试或等效的互联网连接速度测试 GitHub上有一个项目叫速度检查 https gi
  • 为什么需要设置WORKON_HOME环境变量?

    我已经有一段时间没有使用 python 虚拟环境了 但我也安装了虚拟环境包装器 我的问题是 在文档页面中它说要这样做 export WORKON HOME Envs mkdir p WORKON HOME source usr local
  • 使用会话在 Django 中将文件从一个视图传递到另一个视图

    我当前的工作项目要求我允许用户上传各种格式的文件 目前仅处理 CSV 格式 然后使用包含的数据来绘制图表Pandas http pandas pydata org 图书馆 我决定将图形渲染到模板的最简单方法是为图形创建特定视图 然后将图像从
  • 使用 python 脚本更改 shell 中的工作目录

    我想实现一个用户态命令 它将采用其参数之一 路径 并将目录更改为该目录 程序完成后 我希望 shell 位于该目录中 所以我想实施cd命令 但需要外部程序 可以在 python 脚本中完成还是我必须编写 bash 包装器 Example t
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • Python脚本从字母和两个字母组合生成单词

    我正在编写一个简短的脚本 它允许我使用我设置的参数生成所有可能的字母组合 例如 b a 参数 单词 5 个字母 第三 第五个字母 b a 第一个字母 ph sd nn mm 或 gh 第二 第四个字母 任意元音 aeiouy 和 rc 换句
  • 在Python中使用pil读取tif图像时出现值错误?

    我必须读取尺寸的tif图像2200 2200并输入 uint16 我将 PIL 库与 anaconda python 一起使用 如下所示 from PIL import Image img Image open test tif img i
  • 将 Django 中的所有视图限制为经过身份验证的用户

    我是 Django 新手 我正在开发一个项目 该项目有一个登录页面作为其索引和一个注册页面 其余页面都必须仅限于登录用户 如果未经身份验证的用户尝试访问这些页面 则必须将他 她重定向到登录页面 我看到 login required装饰器会将
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO
  • 用 pandas DataFrame 替换 mysql 数据库表中的行

    Python 版本 2 7 6 熊猫版本 0 17 1 MySQLdb 版本 1 2 5 在我的数据库中 PRODUCT 我有一张桌子 XML FEED 表 XML FEED 很大 数百万条记录 我有一个 pandas DataFrame
  • 检查 IP 地址是否在给定范围内

    我想检查一下是否有IP180 179 77 11位于特定范围之间 例如180 179 0 0 180 179 255 255 我编写了一个函数 它将每个 IP 八位字节与其他八位字节进行比较 def match mask IP min ip
  • 如何有效地比较 pandas DataFrame 中的行?

    我有一个 pandas 数据框 其中包含雷击记录以及时间戳和全球位置 格式如下 Index Date Time Lat Lon Good fix 0 1 20160101 00 00 00 9962692 7 1961 60 7604 1
  • py2exe ImportError:没有名为 的模块

    我已经实现了一个名为 myUtils 的包 它由文件夹 myUtils 文件 组成 init py 和许多名称为 myUtils 的 py 文件 该包包含在 myOtherProject py 中 当我从 Eclipse 运行它们时可以找到
  • 超过两个点的Python相对导入

    是否可以使用路径中包含两个以上点的模块引用 就像这个例子一样 Project structure sound init py codecs init py echo init py nix init py way1 py way2 py w

随机推荐

  • 使用 Modernizr 测试平板电脑和移动设备 - 征求意见

    我想使用 Modernizr 来检测用户是否在台式机 平板电脑或移动设备上查看网站 我最初的第一个想法显然是检查屏幕尺寸是否足以满足移动设备和更大的桌面的需求 对于屏幕尺寸也可以等于小型桌面屏幕 1024 x 768 的平板电脑设备 我也会
  • 使应用程序启动并保持横向模式

    如何以横向模式启动我的应用程序 并保持屏幕旋转 BOOL shouldAutorotateToInterfaceOrientation UIInterfaceOrientation interfaceOrientation return i
  • 如何限制推导式的大小?

    我有一个list并想要构建 通过理解 另一个列表 我希望通过一个条件限制这个新列表的大小 下面的代码将会失败 a 1 2 1 2 1 2 b i for i in a if i 1 and len b lt 3 with Traceback
  • 如何在 Windows 上限制进程的 CPU 使用率? (需要代码,而不是应用程序)

    有一些程序可以限制 Windows 中进程的 CPU 使用率 例如BES http mion faireal net BES and 线程大师 http threadmaster tripod com 我需要编写自己的程序 该程序与这些程序
  • 编写一个带有两个参数的 forAll 过程:系列的开始值和结束值,并将给定过程应用于该系列

    我正在尝试编写一个带有两个参数的 forAll 过程 一系列的开始值和结束值 生成的闭包还需要两个参数 一个应用于系列中所有元素的操作 以及一个初始值 这就是我所拥有的 我似乎遗漏了一些东西或者我不理解闭包背后的概念 define forA
  • 在 python 中处理大输入

    我几个月前开始学习编程 最近发现codechef http codechef com 问题是 对于使用大量输入的问题 我的代码总是超出时间限制 我什至似乎无法做到输入测试 http www codechef com problems INT
  • 变量嵌套 for 循环

    我试图弄清楚如何使用递归来执行 n 级嵌套 for 循环 例如 如果 n 3 则将有 3 个 级别 for z 0 z lt 6 z for y 0 y lt 6 y for x 0 x lt 6 x if z y x f do somet
  • Haskell:通用 IORef、MVar?

    我创建了以下特定于 IO monad 的函数 memoIO MonadIO m gt m a gt IO m a memoIO action do ref lt newMVar Nothing return do x lt maybe ac
  • ASPX 和 WinForms 之间如何通信

    如何从 ASPX 网页向 WinForms 应用程序发送命令 我们已经探索过使用不同的命令行参数执行 WinForms 应用程序 但想要更智能的东西 Thanks 在您的应用程序中创建一个侦听 HTTP 的 Web 服务器GET and o
  • PullRefreshIndicator 与 ScrollableTabRow 重叠

    我开始了解 Jetpack Compose 我把这个放在一起app https github com 4gus71n TheOneApp在我探索不同的日常用例时 该项目中的每个功能模块都应该解决不同的场景 该功能模块之一 chatexamp
  • 图像缩放类型在颤动上居中裁剪?

    我正在尝试做一些类似于 android ImageView 的 centerCrop 属性的事情 设置imageview的高度 并使其裁剪并对齐到中心 就像centerCrop在android上的工作一样 Widget bindItem B
  • C 中的暂定定义和链接

    考虑由两个文件组成的 C 程序 f1 c int x f2 c int x 2 我对第6 9 2段的阅读C99标准 http www open std org JTC1 SC22 wg14 www docs n1124 pdf是这个计划应该
  • 是什么导致不可变对象在没有安全发布技术的情况下被发布?

    即使不诉诸安全发布习惯用法 也可以发布不可变对象 这是什么意思 我读过了Java 并发实践 第3章 共享对象 但仍然无法理解该声明 不可变对象可以通过任何机制发布 V S 应该安全地发布有效的不可变对象 编辑 我经历过SO类似的问题 htt
  • 在 Java 中,/(即正斜杠)在 $Lambda$15/0x00000008000a9440@32e6e9c3 等对象引用中意味着什么?

    在 JShell 中 如果我这样做 interface Foo String foo Foo gt hi I get created interface Foo 2 gt Lambda 15 0x00000008000a9440 32e6e
  • 如何在 Java 中使用 Blender 模型?

    真的只是一个一般性问题吗 假设我正在制作一款游戏 并在 Blender 中制作了一个角色模型 我将如何在 Java 中使用这个模型 我会以某种方式导入它吗 Thanks 通常 在搅拌机中制作模型时 您可以以某种格式导出模型 以便稍后将其导入
  • Django 重写模型 Clean() 与 Save()

    保存模型时 我需要执行一些操作 尤其是从管理员那里执行 我将几个字段大写并检查以确保其中一个字段或另一个字段已填充 我还创建了场蛞蝓 现在 这些功能被分为覆盖清理和保存功能 它现在可以使用 但我很好奇何时使用它们 我浏览了文档 但找不到具体
  • 如何从 .js 文件中的 jQuery 函数访问 PHP 会话变量?

    如何从 js 文件中的 jQuery 函数访问 PHP 会话变量 在此代码中 我想从会话变量中获取 值 function progressbar progressbar value 37 您可以通过 PHP 生成 javascript 文件
  • 自定义 UITableView 动态单元格高度

    我搜索了无数博客和文章 了解如何确定自定义 UITableViewCell 的动态高度及其详细文本 我真的很难找到任何关于这方面的好的文档 我需要做的是让单元格根据里面的文本生长 但高度永远不要低于 70 我已经在 StackOverflo
  • c++ 传递数组而不是可变长度参数列表

    所以我有一个采用可变长度参数列表的函数 例如 int avg int count stuff 我可以用它来称呼它avg 4 2 3 9 4 而且效果很好 它需要维护这个功能 有没有办法让我也用数组来调用它而不是列出变量 例如 avg 4 m
  • Django 模型中没有此类列错误

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