OperationalError,没有这样的列。 Django的 [英] OperationalError, no such column. Django

查看:1951
本文介绍了OperationalError,没有这样的列。 Django的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  / snippets / 
中的OperationalError没有这样的列:snippets_snippet.owner_id
请求方法:GET
请求URL:http:// localhost:8000 / snippets /
Django版本:1.7
异常类型:OperationalError
异常值:
否这样的列:snippets_snippet.owner_id
异常位置:/Users/taylorallred/Desktop/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py执行,行485
Python可执行文件:/ Users / taylorallred / Desktop / env / bin / python
Python版本:2.7.5
Python路径:
['/ 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',
'/系统/库/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']
服务器时间:星期六,11十一月2014 07:02:34 +0000

我已经在网络上的几个地方看过,而不仅仅是解决方案的stackoverflow,似乎在ge问题是我的数据库,需要删除它,然后重新制作,我已经做了这几次,教程甚至有我删除数据库并重绘在一点。
这是我的 models.py

  from django .db导入模型
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
从pygments导入突出显示


LEXERS = [项目在get_all_lexers()中的项目如果项目[1]]
LANGUAGE_CHOICES = sorted([(item [1] [0]项目[0])对于LEXERS中的项目)
STYLE_CHOICES = sort((item,item)for item in get_all_styles())



class Snippet
owner = models.ForeignKey('auth.User',related_name ='snippets')
highlight = models.TextField()
created = models.DateTimeField(auto_now_add =
title = models.CharField(max_length = 100,blank = True,default ='')
code = models.TextField()
linenos = models.BooleanField(default = False)
language = models.CharField(choice s = LANGUAGE_CHOICES,
default ='python',
max_length = 100)
style = models.CharField(choices = STYLE_CHOICES,
default ='friendly',
max_length = 100)
class Meta:
order =('created',)
def save(self,* args,** kwargs):

使用'pygments'库创建代码片段的突出显示的HTML
表示形式。

lexer = get_lexer_by_name(self.language)
linenos = self.linenos和'table'或False
options = self.title和{'title':self .title}或{}
formatter = HtmlFormatter(style = self.style,linenos = linenos,
full = true,** options)
self.highlighted = highlight(self.code, lexer,formatter)
super(Snippet,self).save(* args,** kwargs)

我的 serializers.py

  from django.forms import小部件
从rest_framework导入序列化程序
从snippets.models导入代码片段,LANGUAGE_CHOICES,STYLE_CHOICES
从django.contrib.auth.models导入用户



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


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


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

我的 views.py

 从snippets.models导入Snippet 
从snippets.serializers导入SnippetSerializer
从rest_framework import generics
从django.contrib.auth.models import User
from snippets.serializers从rest_framework导入权限导入UserSerializer


类SnippetList(generics.ListCreateAPIView):

列出所有片段,或创建新的片段。

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

检索,更新或删除一个nippet实例。

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

最后我的 urls.py



<$ p $来自django.conf.urls import的p> 包含来自django.conf.urls导入模式的
,来自rest_framework.urlpatterns的url
import format_suffix_patterns
从片段导入视图


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')),

如果我发了一堆不必要的信息,我很抱歉。感谢提前的家伙。



编辑:
DB模式:

  CREATE TABLEsnippets_snippet(idinteger NOT NULL PRIMARY KEY AUTOINCREMENT,
createddatetime NOT NULL,titlevarchar(100)NOT NULL,codetext NOT NULL,
linenosbool NOT NULL,languagevarchar(100)NOT NULL,stylevarchar(100)NOT NULL);

在做了一些挖掘之后,我发现当删除并重新创建数据库(正如教程所说)使用 makemigrations 命令,它不仅不会添加列,但它也不会告诉我有什么不对,当运行 makemigrations 命令它告诉我:

 你正在尝试添加一个不可为空的字段高亮显示到没有默认; 
我们不能这样做(数据库需要填充现有行的东西)。
请选择一个修复:
1)现在提供一次性默认(将在所有现有行上设置)
2)退出,并让我在models.py $中添加一个默认值b $ b

如果我注释了突出显示的 code> models.py 它将发布上面相同的消息,但对于所有者行。所以它需要默认为突出显示所有者,但我不知道该用什么。除了教程不能帮助我。

解决方案

当您浏览教程时,您必须遇到关于迁移的部分,因为这是django的一个主要变化1.7



在django 1.7之前,syncdb命令从未发生任何有机会破坏数据的更改目前在数据库中。这意味着如果您为模型执行了syncdb,则向模型添加新行(有效地添加了一个新列),syncdb不会影响数据库中的更改。



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



然后一个项目被称为 south ,实现了迁移。这意味着有一种方法可以向数据库迁移(并反向,撤销)任何更改,并保留数据的完整性。



在django 1.7中,功能 south 直接集成到django中。在进行迁移时,流程有所不同。


  1. 更改为 models.py (正常)。

  2. 创建迁移。这将生成从当前状态到模型的下一个状态的代码。这是通过 makemigrations 命令完成的。这个命令足够聪明,可以检测出什么变化,并且将创建一个脚本来实现对数据库的更改。

  3. 接下来,您将使用 migrate 。此命令将按顺序应用所有迁移。

所以你的普通 syncdb 现在 python manage.py makemigrations ,后跟 python manage.py migrate



现在,关于您的具体问题:

 类Snippet(models.Model):
owner = models.ForeignKey('auth.User',related_name ='snippets')
highlight = 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 ='
max_length = 100)

在这个模型中,你有两个字段高亮显示代码(必须不能为空)



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



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



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


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 :

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 point. Here is my 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:

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:

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

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 makemigrations command it would not only NOT add the columns but it would also not tell me something was wrong, when running the makemigrations command it tells me:

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 highlighted section in models.py it will post the same message above but for the owner line. So it wants a default for both highlighted and owner, but I am not sure what to use as it. As well as the tutorial isn't helping me either on it.

解决方案

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

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.

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.

Then a project came along called south which 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.

In django 1.7, the functionality of south was integrated directly into django. When working with migrations, the process is a bit different.

  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 makemigrations command. 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.

So your normal syncdb is now a two step process, python manage.py makemigrations followed by 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 highlighted and code that are required (they cannot be null).

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.

这篇关于OperationalError,没有这样的列。 Django的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆