Home > database >  django foreign key mismatch - "question_question" referencing "question_subject"
django foreign key mismatch - "question_question" referencing "question_subject"

Time:11-21

Hi there is this problem I have can anyone solve this ?

here is my django model

class Question(models.Model):
    user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True)
    title = models.CharField(max_length=255,null=True,blank=False)
    content = models.TextField(null=True,blank=False)
    subject = models.ForeignKey(Subject,on_delete=models.SET_NULL,null=True,related_name="subject_question")
    topicTag = models.ManyToManyField(TopicTag, related_name='questionTopic', blank=True)
    image = models.ImageField(blank=True, null=True)
    createdAt = models.DateTimeField(auto_now_add=True)
    votes = models.ManyToManyField(User, related_name='questionUser', blank=True, through='QuestionVote')
    answer_count = models.IntegerField(default=0,null=True,blank=True)
    difficulty = models.ForeignKey(Difficulty,on_delete=models.SET_NULL,null=True,related_name="difficulty")
    id = models.UUIDField(default=uuid.uuid4,  unique=True, primary_key=True, editable=False)

    def __str__(self):
        return self.title


and here is the error code

django.db.utils.OperationalError: foreign key mismatch - "question_question" referencing "question_subject"

and here is the subject model

class Subject(models.Model):
    name = models.CharField(max_length=255,primary_key=True,null=False,blank=False)
    
    def __str__(self):
        return self.name

CodePudding user response:

This error is likely do to a migration issue. If you are in early development, the quickest solution is to delete migration files and SQLite db, re-run python manage.py makemigrations and python manage.py migrate. Alternatively you can revert all migrations with python manage.py name_of_app migrate -- zero.

See here for more information on reverting migrations.

  • Related