Django中增加字段修改数据表的方法

时间:2022-01-18 12:24:09

 1, 在Modle中增加新的属性;
class Animal(models.Model):
name = models.CharField(max_length=20)
sound = models.CharField(max_length=20)
weight = models.IntegerField() # 新加字段
 
2, 执行python manage.py sql animal (APP名),查看创建表的SQL语句:
E:\mysite>python manage.py sql animals
BEGIN;
CREATE TABLE `animals_animal` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(20) NOT NULL,
`sound` varchar(20) NOT NULL,
`weight` integer NOT NULL
)
;
COMMIT;

3, 执行python manage.py dbshell,进入MySQL终端;
4, 在MySQL终端中执行 ALTER TABLE animals_animal ADD COLUMN `weight` integer NOT NULL;
5,查看修改结果, 在MySQL终端中执行:DESC animals_animal;
6,增加外键字段:
class Animal(models.Model):
user = models.ForeignKey(User) # 新加字段
name = models.CharField(max_length=20)
sound = models.CharField(max_length=20)
weight = models.IntegerField()
 
执行上面第2步得到如下输出:
E:\mysite>python manage.py sql animals
BEGIN;
CREATE TABLE `animals_animal` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`user_id` integer NOT NULL,
`name` varchar(20) NOT NULL,
`sound` varchar(20) NOT NULL,
`weight` integer NOT NULL
)
;
ALTER TABLE `animals_animal` ADD CONSTRAINT `user_id_refs_id_36c50bc` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);

 
执行上面第3步进入MySQL终端
执行下面两条SQL语句:
ALTER TABLE animals_animal ADD COLUMN `user_id` integer NOT NULL;
ALTER TABLE `animals_animal` ADD CONSTRAINT `user_id_refs_id_36c50bc` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);