I am working on the following two Django models:
Organisation model which has the User as Foreign key and the Category list which has the Organisation as its Foreign Key
Following are the Models:
# 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'
Now I have got a huge list of 150+ values stored in my settings.py file which I want to add within the Category model.
The CATEGORY_LIST = ['value', 'value2', ...., 'valueN'] looks like this
This is the script I am executing in 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)
However I am encounter the following error:
django.db.utils.OperationalError: foreign key mismatch - "Mysite_category" referencing "Mysite_organisation"
where: Mysite is my app name in Django project.
Please help! Thanks
UPDATE: Solution:
The Python interpreter was incorrectly referencing the 'Organisation' model and not the 'organisation' field of the 'Category' model, it was a naming convention problem. I have now resolved it
答案 0 :(得分:0)
(代表问题作者发布的解决方案)。
Python解释器错误地引用了“组织”模型而不是“类别”模型的“组织”字段,这是一个命名约定问题。我现在已经解决了
答案 1 :(得分: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就好了。