简体   繁体   中英

IntegrityError Primary Key Invalid (python-django)

I'm looking at a sentdex lesson and I have this error and why ?

I saw a similar question here but couldn't get the answer


from django.db import models
from datetime import datetime
# Create your models here.

class tutorialcategory(models.Model):
    tutorial_category=models.CharField(max_length=200)
    category_summary=models.CharField(max_length=200)
    category_slug=models.CharField(max_length=200, default=1)

    class Meta:
        verbose_name_plural="Categories"

    def __str__(self):
        return self.tutorial_category

class tutorialseries(models.Model):
    tutorial_series=models.CharField(max_length=200)
    tutorial_category=models.ForeignKey(tutorialcategory,  verbose_name="Category",  on_delete=models.SET_DEFAULT)
    series_summary=models.CharField(max_length=200)

    class Meta:
        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, default=1, verbose_name="series", on_delete=models.SET_DEFAULT)
    tutorial_slug=models.CharField(max_length=200, default=1)

    def __str__(self):
        return self.tutorial_title

Below is how the error looks like:

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 value '1' that does not have a corresponding value in main_tutorialseries.id.

Answer:

On tutorial model do you have a foreign key tutorial_series defined as:

tutorial_series=models.ForeignKey(tutorialseries, default=1, ...

This FK (Foreign Key) has as default value 1 , but, when you execute your code, you are trying to save a tutorial but they are not any tutorial_series with Id = 1 .

Try to create a tutorialseries (with Id=1) or just change the default value to None. Like this:

tutorial_series=models.ForeignKey(tutorialseries, null=True, blank=True, ...

About your question:

You set a title of this post:

IntegrityError Primary Key Invalid (python-django)

But, what is invalid, is not the Primary Key. What is invalid is the foreign key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM