简体   繁体   English

django.db.utils.IntegrityError:

[英]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. django.db.utils.IntegrityError:主键为“1”的表“main_tutorial”中的行具有无效的外键:main_tutorial.tutorial_series_id 包含的值“tutorial_series_id”在 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.只需从“main()”以及 db.sqlite 文件中删除“migrations”文件夹即可。

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.错误可能是因为我们已经在 db 中有 Tutorial 而没有链接到 TutorialSeries 所以..,要使其链接到 db,进行上面的更改,然后再次执行命令。

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.确保在执行这些命令时已将 Tutorial 与 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:您可以简单地从 django shell 中删除 main_tutorial 表中的所有对象:

  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.这将删除 Tutorial 表中的所有对象,然后进行迁移和迁移,它应该可以正常工作。

In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **.在您的Tutorial模型中,您使用的是外键字段 ** 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.这会导致迁移检查TutorialSeries中是否存在id=1的记录,但不存在此类数据,因此发生错误。

To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:为避免迁移时出现错误,请从我们的字段中删除on_delete=models.SET_DEFAULTdefault=1以使您的模型为:

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 .然后将数据添加到id=1TutorialCategoryTutorialSeries中。

Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT) .然后将模型恢复为初始设置(保持 default=1 和 on_delete=models.SET_DEFAULT) Then again run makemigrations and migrate your models.然后再次运行 makemigrations 并迁移您的模型。 After this, your problem might be solved.在此之后,您的问题可能会得到解决。

Try to delete all the migration files exept __init__.py and also delete db.sqlite3.尝试删除所有迁移文件 exept __init__.py并删除 db.sqlite3。 After that run makemigrations and migrate again之后运行 makemigrations 并再次迁移

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

I was dealing with the same issue.我正在处理同样的问题。 I deleted everything inside migrations except _init__.py and also the sqlite database.我删除了迁移中的所有内容,除了 _init__.py 和 sqlite 数据库。 Then ran- py -3.7 manage.py makemigrations, then after that, py -3.7 manage.py migrate.然后运行 ​​py -3.7 manage.py makemigrations,然后再执行 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.上面的答案可能是正确的,但它对我不起作用,因为 -im 使用 postgres,我不能只删除数据库 -migration 文件是在 git 中提交的。

My situation was, I have 004 migration file but i cant run it because of IntegrityError.我的情况是,我有 004 迁移文件,但由于 IntegrityError,我无法运行它。

I checked the file, and i saw it was in operation list.我检查了文件,我看到它在operation列表中。

The first item of list is migrations.CreateModel and the second was migrations.AddField列表的第一项是migrations.CreateModel ,第二项是migrations.AddField

here are my steps:这是我的步骤:

  1. I commented the second item in list, only the CreateModel is remaining.评论了列表中的第二项,只剩下CreateModel

  2. then run the migrate然后运行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.打开 django 管理页面并手动添加缺少的 id,您也可以在数据库编辑器或update语句中添加它。

  4. uncomment the AddField section and rerun the migrate .取消注释AddField部分并重新运行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"但请记住,在完成“python3 manage.py makemigrations”和“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".以下答案由好人发布在 senddex 的 Django 教程评论上,即:“Kevin di”和“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.在你的工作目录中有一个文件“db.sqlite3”,你可以使用任何支持 SQLite 类型的数据库管理工具打开它。 following the steps:遵循以下步骤:

  1. For example, " DB Browser for SQLite ", you can Google and download it.比如“DB Browser for SQLite”,你可以谷歌下载。
  2. Opening the " db.sqlite3 " file, navigate to the Tables.打开“ db.sqlite3 ”文件,导航到表。
  3. Find the main_tutorial table.找到 main_tutorial 表。 (Maybe you used another table name in the previous lessons, use your table name.) (也许您在之前的课程中使用了另一个表名,请使用您的表名。)
  4. Delete record from the table: main_tutorial.从表中删除记录:main_tutorial。
  5. Try python manage.py migrate again.再次尝试 python manage.py migrate。

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从表中删除记录的含义可以解释为: - 单击 main_tutorial - 然后您可能会看到一个名称为 Browse Data 的选项卡 - 单击它,您将看到您的记录 - 在左侧的数字上按 Ctrl + 鼠标左键用于选择所有行的手侧列 - 使用右键单击删除它们

Delete migration files from the folder except从文件夹中删除迁移文件,除了

__init__.py

Then:然后:

python manage.py makemigrations
python manage.py migrate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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