【发布时间】:2018-01-13 10:22:50
【问题描述】:
我似乎不明白这个错误或如何解决它。我对 django 模型有些不理解。
考虑一下当我尝试在Keyword 模型上执行get_or_create 时会发生什么。这是模型,以及我在 shell 中编写的一些代码。
@python_2_unicode_compatible
class Keyword(models.Model):
word = models.CharField(max_length=200)
statement = models.ManyToManyField(Statement)
def __str__(self):
return self.word
>>> from gtr_site.models import *
>>> a = Statement()
>>> Keyword.objects.get_or_create(word="Testkeyword", statement=a)
Traceback (most recent call last): ...
ValueError: "<Keyword: Testkeyword>" needs to have a value for field "keyword" before this many-to-many relationship can be used.
但如果你只是写 Keyword.objects.get_or_create(word="TestKeyWord")(所以如果你完全排除语句实例),那么错误就会消失。
我真的不明白这个错误是如何发生的,因为...Statement 模型和 Keyword 模型实际上都没有一个名为“关键字”的字段。
但是,Statement 模型确实有很多组件。这是它的代码。
@python_2_unicode_compatible
class Statement(models.Model):
statement_id = models.CharField(max_length=200)
title = models.CharField(max_length=200)
issue_date = models.DateField("Issue-Date")
author = models.ForeignKey(Person)
released_by = models.ForeignKey(Organization)
keywords = models.ManyToManyField('KeywordInContext')
solokeywords = models.ManyToManyField('Keyword', related_name='statement_keywords')
为了清楚起见,我选择排除模型中的另外三个选择字段。
Statements 模型中只有一个字段实际上确实有一个称为关键字的字段。与KeywordInContext创建ManyToMany关系的字段“keywords”该模型如下:
@python_2_unicode_compatible
class KeywordInContext(models.Model):
keyword = models.ForeignKey(Keyword)
contexts = models.ManyToManyField(Keyword, related_name='keyword_context')
def __str__(self):
return self.keyword.word + ' (' + ', '.join(c.word for c in self.contexts.all()) + ')'
需要注意的重要一点是 field 关键字为 Keyword 对象创建了一个 ForeignKey。
所以...我仍然不明白这是怎么回事。当我尝试创建同时具有 word 和 statement 字段作为参数的新关键字时,我不明白为什么 KeyInContext 中的字段甚至变得相关。对此,我如何创建一个Keyword 对象,同时指定了word 和statement 参数?
【问题讨论】:
标签: python django django-models models