【问题标题】:django models Values error preventing me from creating a model with fields specified as parameters?edjango 模型值错误阻止我创建具有指定为参数的字段的模型?e
【发布时间】: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。

所以...我仍然不明白这是怎么回事。当我尝试创建同时具有 wordstatement 字段作为参数的新关键字时,我不明白为什么 KeyInContext 中的字段甚至变得相关。对此,我如何创建一个Keyword 对象,同时指定了wordstatement 参数?

【问题讨论】:

    标签: python django django-models models


    【解决方案1】:

    错误试图告诉您需要先保存关键字对象,然后才能通过多对多链接到它。您还需要保存声明;这是因为m2m关系涉及到一个链接表,所以双方都需要ID才能链接它们。换句话说,您不能在 create 调用中分配 m2m 字段。

    至于为什么您会收到该特定消息,我猜您在内存中有旧版本的模型,您将主键字段定义为keyword

    【讨论】:

    • 嗨。我开始做一些测试,实际上是在暗示你所说的。但是 .save() 在上下文中并不能很好地工作。我执行Statement.objects.update_or_create()(尽管目前,我不会在更新或创建时保存实例)。接下来是我得到刚刚更新或创建的 Statement 对象。 cur_statement = Statement.objects.get_or_create(statement_id = statement["statement_id"]) 但是如果我尝试保存它...cur_statement.save() 给出错误'tuple' object has no attribute 'save'
    • 没关系。我让它完全按要求工作。我将用我使用的代码(或基本上总结)提供答案
    • 我的愚蠢错误。花了一天时间没有意识到您不能在 create 调用中分配 m2m 对象。
    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 2013-03-07
    • 2015-04-16
    • 2019-02-13
    • 2020-06-06
    • 1970-01-01
    • 2019-06-18
    • 2011-10-23
    相关资源
    最近更新 更多