django.db.utils.OperationalError:Shell命令forloop中的外键不匹配 [英] django.db.utils.OperationalError: foreign key mismatch in Shell command forloop

查看:255
本文介绍了django.db.utils.OperationalError:Shell命令forloop中的外键不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

以下是模型:

# 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多个值的庞大列表,我想在类别"模型中添加.

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.

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

The CATEGORY_LIST = ['value', 'value2', ...., 'valueN'] looks like this

这是我正在shell中执行的脚本:

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)

但是我遇到以下错误:

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

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

where: Mysite is my app name in Django project.

推荐答案

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

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

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

这篇关于django.db.utils.OperationalError:Shell命令forloop中的外键不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆