django.db.utils.OperationalError: foreign key mismatch in Shell command forloop

风流意气都作罢 提交于 2019-12-08 12:19:01

问题


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.


回答1:


(Posted solution on behalf of the question author).

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



来源:https://stackoverflow.com/questions/54075787/django-db-utils-operationalerror-foreign-key-mismatch-in-shell-command-forloop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!