Python OperationalError,没有这样的列。姜戈

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26312219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:21:08  来源:igfitidea点击:

OperationalError, no such column. Django

pythondjangodjango-rest-framework

提问by TaylorAllred

I am very new to django and was able to finish the tutorial on djangoproject.com without any errors. I am now going through the Django REST framework tutorial found at http://www.django-rest-framework.org/I am almost finished with it and just added authentication. Now I am getting :

我是 django 的新手,并且能够在 djangoproject.com 上完成教程而没有任何错误。我现在正在浏览http://www.django-rest-framework.org/ 上的 Django REST 框架教程, 我几乎完成了它,只是添加了身份验证。现在我得到:

OperationalError at /snippets/
no such column: snippets_snippet.owner_id
Request Method: GET
Request URL:    http://localhost:8000/snippets/
Django Version: 1.7
Exception Type: OperationalError
Exception Value:    
no such column: snippets_snippet.owner_id
Exception Location: /Users/taylorallred/Desktop/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 485
Python Executable:  /Users/taylorallred/Desktop/env/bin/python
Python Version: 2.7.5
Python Path:    
['/Users/taylorallred/Desktop/tutorial',
 '/Users/taylorallred/Desktop/env/lib/python27.zip',
 '/Users/taylorallred/Desktop/env/lib/python2.7',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-darwin',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac',
 '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/Extras/lib/python',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-tk',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-old',
 '/Users/taylorallred/Desktop/env/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/taylorallred/Desktop/env/lib/python2.7/site-packages']
Server time:    Sat, 11 Oct 2014 07:02:34 +0000

I have looked in several places on the web, not just StackOverflow for the solution, it seems like in general that the problem is with my database and need to delete it then remake it, I have done this several times, the tutorial even has me delete the database and remake it at the point. Here is my models.py:

我在网上找了几个地方,不仅仅是 StackOverflow 的解决方案,一般来说问题出在我的数据库上,需要删除它然后重新制作它,我已经做过几次了,教程甚至有我删除数据库并在此时重新制作它。这是我的models.py

from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight


LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())



class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name='snippets')
    highlighted = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                            default='python',
                                            max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                                     default='friendly',
                                     max_length=100)
    class Meta:
        ordering = ('created',)
def save(self, *args, **kwargs):
    """
    Use the 'pygments' library to create a highlighted HTML
    representation of the code snippet.
    """
    lexer = get_lexer_by_name(self.language)
    linenos = self.linenos and 'table' or False
    options = self.title and {'title': self.title} or {}
    formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                      full=true, **options)
    self.highlighted = highlight(self.code, lexer, formatter)
    super(Snippet, self).save(*args, **kwargs)

My serializers.py:

我的serializers.py

from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User



class SnippetSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='owner.username')
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')


class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True)


    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')

My views.py:

我的views.py

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from snippets.serializers import UserSerializer
from rest_framework import permissions

class SnippetList(generics.ListCreateAPIView):
    """
    List all snippets, or create a new snippet.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Retrieve, update or delete a nippet instance.
    """
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    def pre_save(self, obj):
        obj.owner = self.request.user
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

And finally my urls.py

最后我的 urls.py

from django.conf.urls import include
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views


urlpatterns = patterns('',
    url(r'^snippets/$', views.SnippetList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
    url(r'^users/$', views.UserList.as_view()),
    url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
)

urlpatterns = format_suffix_patterns(urlpatterns)

urlpatterns += patterns('',
    url(r'^api-auth/', include('rest_framework.urls',
                                       namespace='rest_framework')),
)

I apologize if I posted a bunch of unnecessary info. Thanks in advance guys.

如果我发布了一堆不必要的信息,我深表歉意。在此先感谢各位。

Edit: DB Schema:

编辑:数据库架构:

CREATE TABLE "snippets_snippet" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
"created" datetime NOT NULL, "title" varchar(100) NOT NULL, "code" text NOT NULL, 
"linenos" bool NOT NULL, "language" varchar(100) NOT NULL, "style" varchar(100) NOT NULL);

After doing some digging I found that when deleting and recreating the DB (as the tutorial says to) instead of using the make migrationscommand it would not only NOT add the columns but it would also not tell me something was wrong when running the make migrationscommand it tells me:

在做了一些挖掘之后,我发现当删除和重新创建数据库(如教程所说)而不是使用make migrations命令时,它不仅不会添加列,而且在运行make migrations它告诉我的命令时它也不会告诉我有什么问题:

You are trying to add a non-nullable field 'highlighted' to snippet without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

If I comment out the highlightedsection in models.pyit will post the same message above but for the ownerline. So it wants a default for both highlightedand owner, but I am not sure what to use as it. As well as the tutorial isn't helping me either on it.

如果我注释掉其中的highlighted部分,models.py则会在上面发布相同的消息,但针对该owner行。所以它想要一个highlightedand的默认值owner,但我不确定使用什么作为它。以及教程也没有帮助我。

采纳答案by Burhan Khalid

As you went through the tutorial you must have come across the section on migration, as this was one of the major changes in Django 1.7

当您阅读本教程时,您一定遇到过有关迁移的部分,因为这是 Django 1.7 中的主要更改之一

Prior to Django 1.7, the syncdb command never made any change that had a chance to destroy data currently in the database. This meant that if you did syncdb for a model, then added a new row to the model (a new column, effectively), syncdb would not affect that change in the database.

在 Django 1.7 之前,syncdb 命令从未进行任何可能破坏数据库中当前数据的更改。这意味着,如果您对模型执行了 syncdb,然后向模型添加了一个新行(实际上是一个新列),syncdb 不会影响数据库中的该更改。

So either you dropped that table by hand and then ran syncdb again (to recreate it from scratch, losing any data), or you manually entered the correct statements at the database to add only that column.

因此,要么您手动删除该表,然后再次运行 syncdb(从头开始重新创建它,丢失任何数据),要么您在数据库中手动输入正确的语句以仅添加该列。

Then a project came along called southwhich implemented migrations. This meant that there was a way to migrate forward (and reverse, undo) any changes to the database and preserve the integrity of data.

然后出现了一个名为south实现迁移的项目。这意味着有一种方法可以向前迁移(和反向、撤消)对数据库的任何更改并保持数据的完整性。

In Django 1.7, the functionality of southwas integrated directly into Django. When working with migrations, the process is a bit different.

在 Django 1.7 中, 的功能south直接集成到 Django 中。使用迁移时,过程略有不同。

  1. Make changes to models.py(as normal).
  2. Create a migration. This generates code to go from the current state to the next state of your model. This is done with the makemigrationscommand. This command is smart enough to detect what has changed and will create a script to effect that change to your database.
  3. Next, you apply that migration with migrate. This command applies all migrations in order.
  1. models.py(正常)进行更改。
  2. 创建迁移。这将生成从模型的当前状态到下一个状态的代码。这是通过makemigrations命令完成的。此命令足够智能,可以检测到发生了哪些更改,并将创建一个脚本来影响对数据库的更改。
  3. 接下来,您使用migrate. 此命令按顺序应用所有迁移。

So your normal syncdbis now a two-step process, python manage.py makemigrationsfollowed by python manage.py migrate.

所以你的正常syncdb现在是一个两步过程,python manage.py makemigrations然后是python manage.py migrate.

Now, on to your specific problem:

现在,谈谈您的具体问题:

class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name='snippets')
    highlighted = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                            default='python',
                                            max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                                     default='friendly',
                                     max_length=100)

In this model, you have two fields highlightedand codethat is required (they cannot be null).

在此模型中,您有两个字段highlightedcode这是必需的(它们不能为空)。

Had you added these fields from the start, there wouldn't be a problem because the table has no existing rows?

如果您从一开始就添加了这些字段,就不会有问题,因为该表没有现有行吗?

However, if the table has already been created and you add a field that cannot be null, you have to define a default value to provide for any existing rows - otherwise, the database will not accept your changes because they would violate the data integrity constraints.

但是,如果表已经创建并且您添加了一个不能为空的字段,则您必须定义一个默认值来为任何现有行提供 - 否则,数据库将不会接受您的更改,因为它们会违反数据完整性约束.

This is what the command is prompting you about. You can tell Django to apply a default during migration, or you can give it a "blank" default highlighted = models.TextField(default='')in the model itself.

这就是命令提示您的内容。您可以告诉 Django 在迁移期间应用默认值,或者您可以highlighted = models.TextField(default='')在模型本身中给它一个“空白”默认值。

回答by Gabriel Gunderson

Let's focus on the error:

让我们专注于错误:

Exception Value: no such column: snippets_snippet.owner_id

异常值:没有这样的列:snippets_snippet.owner_id

Let's see if that's true...

让我们看看这是不是真的......

You can use the manage.py command to access your db shell(this will use the settings.py variables, so you're sure to connect to the right one).

您可以使用 manage.py 命令访问您的 db shell(这将使用 settings.py 变量,因此您一定要连接到正确的)。

manage.py dbshell

You can now show the details of your table by typing:

您现在可以通过键入以下内容来显示表格的详细信息:

.schema TABLE_NAME

Or in your case:

或者在你的情况下:

.schema snippets_snippet

More sqlite commands can be found hereor by issuing a:

可以在此处或通过发出以下命令找到更多 sqlite 命令:

.help

Lastly, end your session by typing:

最后,输入以下内容结束您的会话:

.quit

This doesn't get you out of the woods, but it helps you know what end of the problem to work on :)

这不会让您摆脱困境,但它可以帮助您了解要解决的问题:)

Good luck!

祝你好运!

回答by copser

I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:

我看到我们在这里有同样的问题,我有同样的错误。我想为将来会遇到同样错误的用户写这篇文章。在像@Burhan Khalid 所说的那样对您的类 Snippet 模型进行更改后,您必须迁移表:

python manage.py makemigrations snippets
python manage.py migrate

And that should resolve the error. Enjoy.

这应该可以解决错误。享受。

回答by Abhimanyu Gaurh

I am also faced same problem.

我也面临同样的问题。

If you're adding a new field then it gives the error as no column found.

如果您要添加新字段,则会出现未找到列的错误。

Then you apply make migrationcommand and after that migratecommand Then still same error.. EX...

然后你应用make migration命令并在该migrate命令之后然后仍然相同的错误.. EX ...

 path=models.FilePathField()

Add default value for field

为字段添加默认值

  path=models.FilePathField(default='')

and than apply command

然后应用命令

  python manage.py makemigrations

  python manage.py migrate

It may help you

它可能会帮助你

回答by SpiRail

If your issue is like mine, then this a workaround. The good news is that you wont have to delete your db.

如果您的问题和我的一样,那么这是一种解决方法。好消息是您不必删除数据库。

Check that there isn't some other model that uses this model as a reference.

检查是否有其他模型使用此模型作为参考。

django.db.utils.OperationalError: no such column: parts_part_type.blah

This was only happening to me because I had another model called "product" in a different app called "products" that referenced this model.

这只是发生在我身上,因为我在一个名为“产品”的不同应用程序中有另一个名为“产品”的模型引用了这个模型。

part = models.ForeignKey("parts.Part", related_name="some part", limit_choices_to={'part_type':Part_Type.objects.get(prefix='PART')},)

My solution was:

我的解决方案是:

  1. comment out the other app (in this case prodcuts) from settings.py
  2. python manage.py makemigrations; python manage.py migrate
  3. un-comment the other app so its enabled again.
  4. python manage.py makemigrations; python manage.py migrate
  1. settings.py 中注释掉其他应用程序(在本例中为产品)
  2. python manage.py makemigrations; python manage.py migrate
  3. 取消注释另一个应用程序,使其再次启用。
  4. python manage.py makemigrations; python manage.py migrate

Technically I think I need to change the limit_choices_toreference so

从技术上讲,我认为我需要更改limit_choices_to参考

回答by M Juckes

Taken from Burhan Khalid's answer and his comment about migrations: what worked for me was removing the content of the "migrations" folder along with the database, and then running manage.py migrate. Removing the database is not enough because of the saved information about table structure in the migrations folder.

摘自 Burhan Khalid 的回答和他对迁移的评论:对我有用的是将“迁移”文件夹的内容与数据库一起删除,然后运行 ​​manage.py migrate。由于在迁移文件夹中保存了有关表结构的信息,因此删除数据库是不够的。

回答by Dev Jalla

You did every thing correct, I have been gone through same problem. First delete you db and migrations I solved my adding name of my app in makemigrations:

你做的每一件事都是正确的,我遇到了同样的问题。首先删除你的数据库和迁移我解决了我添加我的应用程序的名称makemigrations

python manage.py makemigrations appname
python manage.py migrate

This will definitely work.

这肯定会奏效。

回答by marw

This error can happen if you instantiate a class that relies on that table, for example in views.py.

如果实例化依赖于该表的类(例如在 views.py 中),则会发生此错误。

回答by hygull

The most direct way of solving this type of problem is just the following 3 steps process:

解决此类问题最直接的方法就是以下 3 个步骤:

  1. Delete all the migration related files from app's migrations folder/directory (these basically starts with 0001, 0002, 0003etc).

  2. Delete/Rename the existing database file named db.sqlite3from App directory.

  3. Now run the following command:

    python manage.py migrate

    Finally execute

    python manage.py createsuperuser

    to perform the administrative tasks (If you want).

  1. 从应用程序的迁移文件夹/目录中删除所有的移民相关的文件(这基本上是与开始000100020003等)。

  2. 从 App 目录中删除/重命名名为db.sqlite3的现有数据库文件。

  3. 现在运行以下命令:

    python manage.py migrate

    最后执行

    python manage.py createsuperuser

    执行管理任务(如果需要)。

回答by Priyank Kodesia

Agree with Rishikesh. I too tried to solve this issue for a long time. This will be solved with either or both of 2 methods-

同意瑞诗凯诗。我也试图解决这个问题很长时间。这将通过两种方法中的一种或两种来解决-

1.Try deleting the migrations in the app's migrations folder(except init.py) and then running makemigrations command

1.尝试删除应用程序迁移文件夹中的迁移(init.py除外),然后运行makemigrations命令

2.If that doesn't work, try renaming the model (this is the last resort and might get a little messy but will work for sure.If django asks "did you rename the model? just press N.").Hope it helps..:)

2.如果这不起作用,请尝试重命名模型(这是最后的手段,可能会有点混乱,但肯定会起作用。如果 django 询问“您是否重命名模型?只需按 N。”)。希望如此帮助..:)