【问题标题】:IntegrityError using q.save(): may not be NULL使用 q.save() 的 IntegrityError:可能不是 NULL
【发布时间】:2012-09-12 15:03:06
【问题描述】:

我不确定为什么会收到错误消息。这里有意见和好处

from polls.models import Word, Results

def detail(request):
    q = Word(type="How do you like")
    q.save()
    Word.objects.get(pk=1)

    q.score_set.create(score=5)
    q.score_set.create(score=4)
    q.score_set.create(score=3)
    q.score_set.create(score=2)
    q.score_set.create(score=1)


    return render_to_response('/$')

模型.py

 from django.db import models


class Word(models.Model):
    type = models.CharField(max_length=200)

    def __unicode__(self):
            return self.type

class Results(models.Model):
    word = models.ForeignKey(Word)
    score = models.IntegerField()

    def __unicode__(self):
            return self.score

错误:

IntegrityError at /
polls_word.score may not be NULLRequest Method: GET 
Request URL: Django Version: 1.4.1 
Exception Type: IntegrityError 
Exception Value: polls_word.score may not be NULL 
Exception Location: /home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 337 
Python Executable: /home/oveledar/.virtualenvs/django/bin/python 
Python Version: 2.6.6 
Python Path: ['/home/oveledar/django/mysite',
 '/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
 '/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/pip-1.0.2-py2.6.egg',
 '/home/oveledar/.virtualenvs/django/lib64/python26.zip',
 '/home/oveledar/.virtualenvs/django/lib64/python2.6',
 '/home/oveledar/.virtualenvs/django/lib64/python2.6/plat-linux2',
 '/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-tk',
 '/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-old',
 '/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-dynload',
 '/usr/lib/python2.6',
 '/usr/lib64/python2.6',
 '/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages'] 

【问题讨论】:

  • 请发布您的实际代码。对于您在这里的模型,Word 没有 score_set - 它有 results_set
  • 不确定您所说的实际代码是什么意思。我有模型、视图、url 和模板。我还没有使用 url 和模板,所以我只是发布了模型和视图。
  • 关键是这段代码会给你显示的那个不同的错误——它会给score_set一个AttributeError
  • 我发布的错误来自此代码。我刚刚又跑了一遍。剩下的代码你会说什么?
  • 只是好奇,为什么要在代码的第 6 行执行此查询?

标签: django


【解决方案1】:

你的表结构不正确,你需要:

class Results(models.Model):
    word = models.ForeignKey(Word)
    score = models.IntegerField(blank=True, null=True)

之后,删除此表并运行命令:

python manange.py syncdb

#blank 选项是否需要此节点以进行表单验证

#null 选项它是为你的数据库(空真或假)

【讨论】:

  • 很遗憾,还是同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多