我正在研究以下两个 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 项目中的应用名称。