4

我正在研究以下两个 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 模型中。

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 项目中的应用名称。

4

2 回答 2

1

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

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

于 2019-06-06T07:46:37.050 回答
0

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-05-26T01:23:27.217 回答