django.db.utils.IntegrityError:

后端 未结 10 599
忘掉有多难
忘掉有多难 2021-01-21 07:47

django.db.utils.IntegrityError: The row in table \'main_tutorial\' with primary key \'1\' has an invalid foreign key: main_tutorial.tutorial_series_id contains a

10条回答
  •  终归单人心
    2021-01-21 08:01

    In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.

    To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:

    class TutorialSeries(models.Model):
        tutorial_series = models.CharField(max_length=200)
        tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
        series_summary = models.CharField(max_length=200)
    
        class Meta:
            #Otherwise we get "Tutorial Serie*ss* in admin"
            verbose_name_plural = "Series"
    
        def __str__(self):
            return self.tutorial_series
    
    class Tutorial(models.Model):
            tutorial_title = models.CharField(max_length=200)
            tutorial_content = models.TextField()
            tutorial_published = models.DateTimeField("date published", default = datetime.now())
            tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
            tutorial_slug = models.CharField(max_length=200,default=1)
    
            def __str__(self):
                return self.tutorial_title
    

    After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.

    Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.

提交回复
热议问题