【问题标题】:Django South Migration Error: Key is Not PresentDjango South 迁移错误:密钥不存在
【发布时间】:2013-10-25 02:57:46
【问题描述】:

我将这些字段添加到我的模型中:

class WatchList(models.Model):
    name = models.CharField(max_length=20)

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList)

成功运行架构迁移:

 >>> $ python2.7 manage.py schemamigration myapp --auto
 + Added model myapp.WatchList
 ? The field 'Thing.watchlist' does not have a default specified, yet is NOT NULL.
 ? Since you are adding this field, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ?  1. Quit now, and add a default to the field in models.py
 ?  2. Specify a one-off value to use for existing columns now
 ? Please select a choice: 2
 ? Please enter Python code for your one-off default value.
 ? The datetime module is available, so you can do e.g. datetime.date.today()
 >>> 0
 + Added field watchlist on myapp.Thing
 Created 0004_auto__add_watchlist__add_field_thing_watchlist.py. You can now apply this migration with: ./manage.py migrate myapp

在尝试执行此操作之前我没有遇到任何问题,但由于某种原因我收到以下错误:

 >>> $ python2.7 manage.py migrate myapp
FATAL ERROR - The following SQL query failed: ALTER TABLE "myapp_thing" ADD CONSTRAINT "watchlist_id_refs_id_1b2eef756112b8e" FOREIGN KEY ("watchlist_id") REFERENCES "myapp_watchlist" ("id") DEFERRABLE INITIALLY DEFERRED;
The error was: insert or update on table "myapp_thing" violates foreign key constraint "watchlist_id_refs_id_1b2eef756112b8e"
DETAIL:  Key (watchlist_id)=(0) is not present in table "myapp_watchlist".

如何成功地将更改迁移到模型?感谢您提供任何可能有帮助的想法!

【问题讨论】:

    标签: python database django migration django-south


    【解决方案1】:

    这是因为您在迁移中将0 指定为默认值。删除迁移并再次运行,这次指定一个空字符串作为默认值。

    如果数据库中已有一些数据,则需要在 ForeignKey 中指定 null=Trueblank=True,否则会中断。

    【讨论】:

    • 好的,谢谢你的想法。我这样做了,这次输入'' 作为默认值。但是,这一次收到了不同的错误:django.db.utils.DatabaseError: column "none" does not exist。我错过了什么吗?感谢您的想法!
    • 好的,请看我的编辑。如果这不起作用,您至少应该从错误消息中获得更多线索。
    • 好吧,嗯,不幸的是,这也不起作用。错误只说:django.db.utils.DatabaseError: column "none" does not exist。还有其他可能有帮助的想法吗?感谢您的任何想法!
    • 哦,等等,我没有意识到你的意思是ForeignKey(WatchList, null=True, blank=True)。相反,我将它放在 WatchList 模型字段本身中,这导致了问题。按照您的建议更改它可以解决问题。谢谢!
    • 仍然适用于 Django 1.10。帮助我解决问题;我刚刚删除了我拥有的单行并摆脱了错误。
    猜你喜欢
    • 2012-08-06
    • 2011-03-31
    • 2015-03-02
    • 1970-01-01
    • 2011-09-28
    • 2011-08-06
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多