python - django 完整性错误,我知道为什么,但不知道如何解决

标签 python django django-models database-migration

我更改了以前的用户模型,现在它继承自 django 的用户模型。

from django.contrib.auth.models import User

class UserProfile(User):
 #fields..

但其他模型指向我以前的模型,现在如果我想迁移,我会收到错误:

(user_id)=(9) does not exist in auth_user table. 

合理的错误消息。但现在我该怎么办?我真的被困住了。我正在使用 django 版本 1.4

我制作了错误的屏幕截图:

enter image description here

最佳答案

你没有说明你正在使用哪个版本的 Django;如果您使用的是 1.5,那么您还需要设置 AUTH_USER_MODEL 来告诉 Django 使用它(有关更多信息,请参阅 auth docs)。如果您使用的是早期版本,您可能根本不想子类化 User 模型,而是创建一个配置文件(如您的类名所示)作为单独的模型,并将其与外键链接(请参阅 old profile docs了解更多信息)。

您在添加父类时是否也更改了模型的名称?您可能想要在 UserProfile 中设置表的名称,以便它与旧名称匹配。来自 Django model docs :

To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.

For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.

To override the database table name, use the db_table parameter in class Meta.

所以像这样的事情就可以解决问题:

class UserProfile(User):
    # other stuff
    class Meta:
        db_table = "myapp_user"

希望这有帮助!

关于python - django 完整性错误,我知道为什么,但不知道如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977909/

相关文章:

django - 您可以从ModelForm访问Django模型 “property”吗?

django - 数据库错误没有这样的表django

python - 点下方的线拟合

android - 模糊测试时在 Android 上进行进程监控

python - 为什么在 Ubuntu 上安装 Pillow 3.0.0 时出现错误?

python - Django 模型可以有硬编码的无类型字段吗?

python - 将值传递给另一个 View django

python - 对数据库多次运行 "python manage.py syncdb"可以吗?

python - 尝试使用 django-subdomains 在我的 django urlpatterns 中查找循环引用?

python - 使用 Django 的评论框架计算 `models.py` 中每个对象的评论