4

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Simran
  • 593
  • 1
  • 14
  • 37

2 Answers2

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

halfer
  • 19,824
  • 17
  • 99
  • 186
  • And how exactly did you resolve the issue of referencing? I have the same problem. – multigoodverse Sep 02 '21 at 10:26
  • @multigoodverse: you would need to ping the question author (Simran) under their question. They won't be notified of your comment, as I posted this answer (as community wiki). – halfer Sep 02 '21 at 20:34
0

Mysite_category has id without PK. Same on second table Mysite_organisation.

CREATE TABLE "Mysite_category" (
"id"    integer NOT NULL,
"name"  varchar(255) NOT NULL,
"description"   text NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);

Focus on id and same query will be for second table. This is not important you have to make id as primary key via this query. There are so many options to do that. Make id as PK, it'll be fine.

halfer
  • 19,824
  • 17
  • 99
  • 186
azhar
  • 351
  • 3
  • 13