我遵循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
最佳答案
您的模型表明从Reporter
到Article
存在一对多关系,即一个Reporter
可以与许多Articles
相关联。同样,由于reporter
模型的Article
字段不可为空,因此每个Article
必须正好关联一个Reporter
。也就是说,您必须首先创建一个Reporter
(类似于您链接到的文档中的示例):
>>> r = Reporter(first_name='John', last_name='Smith', email='[email protected]')
>>> r.save()
然后将您的
Article
与此关联:>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save()