Django在原有表中添加新字段
-
在models.py文件里面添加新字段
-
执行命令
python manage.py makemigrations AppTest(个人App文件名)
,会在该app下建立 migrations目录,并记录下所有的关于modes.py的改动,比如0001_initial.py, 但是这个改动还没有作用到数据库文件
***@bogon *** % python manage.py makemigrations service
Did you rename *** to *** (a TextField)? [y/N] y
Did you rename *** to *** (a TextField)? [y/N] y
Did you rename *** to *** (a TextField)? [y/N] y
......
You are trying to add a non-nullable field *** to tableenv without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
\>>> ''
- 在
makemigrations
之后执行命令python manage.py migrate
,成功的话理论上将该改动作用到数据库文件,比如产生table,修改字段的类型等。也有可能会出现django.db.utils.OperationalError
的报错
***@bogon *** % python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, django_apscheduler, service, sessions
Running migrations:
Applying service.0002_auto_20200611_1832...Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/didi/Library/Python/2.7/lib/python/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/didi/Library/Python/2.7/lib/python/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/Users/didi/Library/Python/2.7/lib/python/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/Users/didi/Library/Python/2.7/lib/python/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1050, "Table *** already exists")
- 输入命令
python manage.py migrate --fake AppTest(个人App文件名)
,可以解决上述报错。
***@bogon *** % python manage.py migrate --fake service
Operations to perform:
Apply all migrations: service
Running migrations:
Applying service.0002_auto_20200611_1832... FAKED
python manage.py migrate成功后没有修改对应数据库表的解决方案
-
以上命令运行成功后,还是有可能会出现没有修改对应数据库表的情况,遇到这种情况可以先在数据库中使用sql语句添加字段
ALTER TABLE 表名 ADD COLUMN '字段名' timestamp NULL DEFAULT ***
-
再使用
python manage.py inspectdb
反向生成对应代码,将其复制至models.py
文件中。
class Tb(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(unique=True, max_length=128)
detail = models.TextField()
status = models.IntegerField()
time = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False//要改成true
db_table = 'Tb'
- 上述操作执行成功,Django和数据库应该就能同步了