【问题标题】:django.db.utils.OperationalError: foreign key mismatch in Shell command forloopdjango.db.utils.OperationalError:Shell 命令 forloop 中的外键不匹配
【发布时间】:2019-06-02 04:48:42
【问题描述】:

我正在研究以下两个 Django 模型:

以用户为外键的组织模型和以组织为外键的类别列表。

以下是模型

# Create your models here.
from django.contrib.auth.models import User
from django.db import models

class Organisation(models.Model):
  user = models.ForeignKey(
    User, 
    on_delete=models.CASCADE,
    null=True
  )
  organisation_name = models.TextField(
    primary_key=True,
    blank=True
  )

  def __str__(self):
    return self.organisation_name


class Category(models.Model):

  # renamed organisation to organisation_name

  organisation_name = models.ForeignKey(
    Organisation, 
    on_delete=models.SET_NULL, 
    null=True
  )
  category = models.TextField(
   blank=True,
   max_length=200
  )

  class Meta:
    verbose_name_plural = 'Category'

现在我的 settings.py 文件中存储了一个包含 150 多个值的庞大列表,我想在类别模型中添加这些值

CATEGORY_LIST = ['value', 'value2', ...., 'valueN'] 看起来像这样

这是我在 shell 中执行的脚本

from Venter.models import Organisation, Category
from Backend import settings

cat_list = settings.CATEGORY_LIST # the list is getting loaded into cat_list
org_name = Organisation.objects.get(organisation_name='ABC') # exists
for x in cat_list:
    Category.objects.create(organisation=org_name, category=x)

但是我遇到了以下错误:

 django.db.utils.OperationalError: foreign key mismatch - "Mysite_category" referencing "Mysite_organisation"

其中:Mysite 是我在 Django 项目中的应用名称。

【问题讨论】:

    标签: django django-models django-shell


    【解决方案1】:

    (代表问题作者发布解决方案)

    Python 解释器错误地引用了“组织”模型,而不是“类别”模型的“组织”字段,这是一个命名约定问题。我已经解决了

    【讨论】:

    • 您究竟是如何解决引用问题的?我也有同样的问题。
    • @multigoodverse:您需要在他们的问题下 ping 问题作者 (Simran)。当我发布此答案(作为社区 wiki)时,他们不会收到您的评论的通知。
    【解决方案2】:

    Mysite_category 的 id 没有 PK。在第二个表 Mysite_organisation 上也是如此。

    CREATE TABLE "Mysite_category" (
    "id"    integer NOT NULL,
    "name"  varchar(255) NOT NULL,
    "description"   text NOT NULL,
    PRIMARY KEY("id" AUTOINCREMENT)
    );
    

    关注 id 和相同的查询将用于第二个表。这并不重要,您必须通过此查询将 id 作为主键。有很多选择可以做到这一点。把id设为PK,就可以了。

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2013-06-05
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      相关资源
      最近更新 更多