django 中 如果没有 primary_key,是否无法建立 model?

2020-12-30 18:08:36 +08:00
 lixuda

老数据表,本身没有 primary_key 是不是必须要指定一个 primary_key ? 之前用过 peewee,可以设置无 primary_key 数据表

2691 次点击
所在节点    Django
11 条回复
eastpiger
2020-12-30 18:11:03 +08:00
django 在没有明确指定 pk 的时候会自动创建一个 pk 字段。

https://kapeli.com/dash_share?docset_file=Django&docset_name=Django&path=doc/ref/models/fields.html%23s-primary-key&platform=django&repo=Main&version=3.1.4

## primary_key
Field.primary_key
If True, this field is the primary key for the model.

If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.

primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.

The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.
lixuda
2020-12-30 18:21:10 +08:00
@eastpiger 已有数据库,不需要建库,有办法吗
virusdefender
2020-12-30 18:23:37 +08:00
@eastpiger django 有 fake migration 等机制用于解决这种问题
eastpiger
2020-12-30 18:24:29 +08:00
@lixuda #2 虽然确实有办法,但是非常复杂。不如写个程序转换一下。
可以在 django 中定义好数据类型,然后 python3 manage.py shell
from xxx.models import YourModel
YourModel.xxxx
这样直接把数据导入进去
heyDemon
2020-12-30 18:27:12 +08:00
你把数据加进去, 默认会有一个自增主键, 只不过对你来说没用而已
lixuda
2020-12-30 20:48:57 +08:00
@eastpiger 另外是否可以 2 个字段 设置 primary key ?
freakxx
2020-12-30 21:33:47 +08:00
@lixuda #6

我觉得应该有办法可以去做些处理,但我最近迷上 go 。
如果回头你还没解决办法,我可以来玩下。

你可以试下从这个角度去看看
python manage.py inspectdb
从 sql 反向成 model
liukun1212
2020-12-31 09:48:25 +08:00
可以自动建立 pk,你迁移一下就自动加进去了。
lixuda
2020-12-31 09:58:07 +08:00
@freakxx 谢谢,模型就是 inspectdb 生成,由于数据表默认没有 pk,所以 model 也没有 pk,导致 model 保存数据提示没有 pk 健
lixuda
2020-12-31 10:21:53 +08:00
@freakxx go 不熟,比 python web 开发效率比?
freakxx
2020-12-31 17:45:57 +08:00
@lixuda #10

简单还是 py 简单,而且很傻瓜式

但我不怎么想写 py 了,感觉太飘。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740386

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX