简体   繁体   中英

django.db.utils.IntegrityError:

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

The above error shows up and cant migrate

These are my models:

    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:
            #Gives the proper plural name for admin
            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, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
        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, 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

I faced the same problem just I am also working with the same. All you got to do is to

just delete "migrations" folder from the "main()" and also the db.sqlite file too.

The error is probably occurring because we have Tutorial already in db which is not linked to TutorialSeries so.., to make it linked to the db, make the changes above and then again perform commands.

What I got was:

python manage.py makemigrations

Output:

No changes detected

Next one

python manage.py migrate

Output:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

Make sure while performing these commands you have linked Tutorial with TutorialSeries. And guys making things done this way makes you earlier data lost from the database. Be careful about that.

Have a Nice day & happy coding.😁

You can simply delete all the objects in the main_tutorial table from django shell:

  1. goto command prompt
  2. python manage.py shell
  3. from main.models import Tutorial
  4. Tutorial.objects.all().delete()

(main being the app name here)

This will delete all the objects in the Tutorial table and then makemigrations and migrate and it should work just fine.

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.

Try to delete all the migration files exept __init__.py and also delete db.sqlite3. After that run makemigrations and migrate again

尝试使用不带默认参数的on_delete = models.CASCADE

I was dealing with the same issue. I deleted everything inside migrations except _init__.py and also the sqlite database. Then ran- py -3.7 manage.py makemigrations, then after that, py -3.7 manage.py migrate. Then it worked!

I had this issue a while ago. The above answer maybe correct but it didnt work for me because -im using postgres, i cant just delete the database -migration files were commited in git.

My situation was, I have 004 migration file but i cant run it because of IntegrityError.

I checked the file, and i saw it was in operation list.

The first item of list is migrations.CreateModel and the second was migrations.AddField

here are my steps:

  1. I commented the second item in list, only the CreateModel is remaining.

  2. then run the migrate

  3. open the django admin page and add it manually the missing id you can add it also in database editor or update statement.

  4. uncomment the AddField section and rerun the migrate .

from django.db import models
from datetime import datetime


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)

    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.CASCADE, blank=True, null=True)
    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, verbose_name="Series", on_delete=models.CASCADE, blank=True, null=True)
    tutorial_slug = models.CharField(max_length=200, default=1)

    def __str__(self):
        return self.tutorial_title

Try this, it's work for me.

But remember, you will need to type this code before you have done "python3 manage.py makemigrations" and "python3 manage.py migrate"

The following answer was been posted on the Django tutorial comments of sentdex by nice folks namely: "Kevin di" and "JOSEPH Blessingh". The recommendation helped me and worked like charm:

There is a file " db.sqlite3 " in your working directory, you can open it with any database management tools that supports SQLite type. following the steps:

  1. For example, " DB Browser for SQLite ", you can Google and download it.
  2. Opening the " db.sqlite3 " file, navigate to the Tables.
  3. Find the main_tutorial table. (Maybe you used another table name in the previous lessons, use your table name.)
  4. Delete record from the table: main_tutorial.
  5. Try python manage.py migrate again.

The meaning of Delete Record from the table can be explained as: - Click main_tutorial - Then you might see a tab with the name Browse Data - Click it and you will see your records - Press Ctrl + Left Mouse button on the number on the left hand side column to select all the rows - Delete them using right click

Delete migration files from the folder except

__init__.py

Then:

python manage.py makemigrations
python manage.py migrate

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