时间:2021-07-01 10:21:17 帮助过:30人阅读
在models.py文件里面创建数据表类,
from django.db import models
class userinfo(models.Model):
uid = models.AutoField(primary_key=True)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
在终端执行数据库创建命令
python3 manage.py makemigrations
python3 manage.py migrate
这里需要注意的是,要在setting里面配置上你的程序,如下图
执行完成后,可以登录到数据库中,查看是否有你创建的数据库表
把username 字段修改为user字段,如何操作?
from django.db import models
class userinfo(models.Model):
uid = models.AutoField(primary_key=True)
user = models.CharField(max_length=32)
password = models.CharField(max_length=64)
执行数据库生成命令,可以看到这里会有提升,询问是否要把那个表下面的那个字段要做调整,这里我们选择Y,回车操作 继续执行下面的命令:
C:\Users\Tony\PycharmProjects\LearnDjango>python3 manage.py makemigrations
Did you rename userinfo.username to userinfo.user (a CharField)? [y/N]
C:\Users\Tony\PycharmProjects\LearnDjango>python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, app01, sessions, auth, contenttypes
Running migrations:
Rendering model states... DONE
Applying app01.0002_auto_20180115_1735... OK
可以看到结果是修改了的
如果我们添加一个字段默认没有给值,则在执行数据库migrations的时候是会有提升,提示结果如下:
C:\Users\Tony\PycharmProjects\LearnDjango>python3 manage.py makemigrations
You are trying to add a non-nullable field ‘age‘ to userinfo without a default; we can‘t do that (the database needs something to populate existing ro
ws).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
解决方法:
我们选择2取消这个提示,这个时候,我们有两种方法解决:
第一种就是设置一个默认值default
from django.db import models
class userinfo(models.Model):
uid = models.AutoField(primary_key=True)
user = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField(default=1)
第二种解决方法是,指定null可以为空
age = models.IntegerField(null=True)
pycharm 使用ORM创建数据库
标签:orm quit 操作 can running end word block name