Django自动为现有数据库表创建主键 [英] Django automatically create primary keys for existing database tables

查看:629
本文介绍了Django自动为现有数据库表创建主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有数据库,我正在尝试使用Django访问.我使用python manage.py inspectdb为数据库创建模型.目前,我能够将模型导入python shell,但是当我尝试以任何方式访问任何实际对象时,都会出现此错误OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'").我看到数据库中的表实际上没有 id 字段.我怎样才能解决这个问题?我是否需要更新 Meta 类中的 managed 字段并运行迁移,以便它可以自动创建此字段?

I have an existing database that I'm trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently I'm able to import the models into the python shell however when I try to access any of the actual objects in any way, I get this error OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'"). I see that the table in the database in fact does not have an id field. How can I fix this? Do I need to update the managed field in the Meta class and run a migration so it can create this field automatically?

推荐答案

来自Django文档:此功能是作为快捷方式,而不是确定的模型生成.有关更多信息,请参见inspectdb的文档. (参考: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)

From the Django documentation: This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information. (Reference: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)

您将需要手动清理模型并迁移.添加"id"字段所需添加的行是:

You're going to need to manually clean up the models and migrate. The line you'll have to add for adding the "id" field is:

id = models.IntegerField(primary_key=True)

警告:我肯定会创建一个数据库副本作为玩具,而不是原始副本.这可能会需要您反复尝试才能正确.绝对确定正确无误后,可以更改Managed=True,但要非常小心!

Warning: I'd definitely create a copy of the database to toy with, rather than the original. This will likely take you some trial and error to get right. After you're absolutely sure you have it right, you can changed Managed=True, but be VERY careful!

这篇关于Django自动为现有数据库表创建主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆