django.db.utils.IntegrityError:NOT NULL约束失败:polls_article.reporter_id

时间:2018-07-17 04:46:53

标签: python django django-models

我正在遵循Django的官方documentation进行多对一关系。

创建新文章,并将其添加到文章集中:

>>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=date(2006, 1, 17))

models.py包括:

从django.db导入模型

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

但是当我尝试执行时,出现错误消息:django.db.utils.IntegrityError:NOT NULL约束失败:polls_article.reporter_id

回溯:

    >>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))

Traceback (most recent call last):
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: polls_article.reporter_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql
    cursor.execute(sql, params)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: polls_article.reporter_id

2 个答案:

答案 0 :(得分:1)

您的模型表明,从ReporterArticle存在一对多的关系,即一个Reporter可以与许多Articles相关联。另外,由于reporter模型的Article字段不能为 为空,因此每个Article 必须都只有一个{{1} }关联。也就是说,您必须首先创建一个Reporter(类似于您链接到的文档中的示例):

Reporter

然后将您的>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com') >>> r.save() 与之关联:

Article

答案 1 :(得分:0)

您正在创建Article实例,而没有reporter 引用,即FK。因此,您需要在创建Article实例时提供FK对象或FK的pk作为在下面,

在[2]中:

reporter = Reporter.objects.create(first_name='Jerin', last_name='Peter George', email='myemail@email.com')

在[3]中:

from datetime import datetime

在[4]中:

Article.objects.create(headline= "Jerin's story", pub_date = datetime.utcnow()<b>,reporter=reporter</b>)

出[4]:

<Article: Paul's story>

如果您希望将报告者对象设置为NULL模型中的Article引用,则必须在模型中通过添加null=True

class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter,
                             <b>null=True,</b> on_delete=models.CASCADE)

def __str__(self):
    return self.headline</code></pre>

因此,您可以创建没有reporter引用的文章对象,作为

new_article2 = Article.objects.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))