需求:
想在模型Critic中添加字段reply_count,并给予初始值0
方法:
先在models.py中修改模型
添加
reply_count = models.IntegerField('回复数')
然后,我们运行命令manage.py sqlall books 来查看create table语句 语句的具体内容取决与你所使用的数据库, 大概是这个样子
CREATE TABLE "move_critic" (
"id" integer NOT NULL PRIMARY KEY,
"title" varchar(100) NOT NULL,
"author_id" integer NOT NULL REFERENCES "auth_user" ("id"),
"moves_id" integer NOT NULL REFERENCES "move_move" ("id"),
"content" text NOT NULL,
"date" datetime NOT NULL,
"reply_count" integer NOT NULL
)
;
接下来,我们要在开发环境上运行数据库客户端,我用的是sqllite,运行 psql, 然后,我执行如下语句
>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute('ALTER TABLE move_critic ADD COLUMN reply_count integer DEFAU
LT 0')
<django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x020C31C0>
最后一句显示添加字段成功!