Django的模型是数据库相关内容,相关代码写在models.py中,Django 支持 sqlite3, MySQL, PostgreSQL等数据库,只需要在settings.py中配置即可,不用更改models.py中的代码
1.首先创建项目、app,将app添加到settings文件中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app', #新注册的app
]
2.修改models.py
from django.db import models
class Myapp_students(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
3.创建数据表(使用默认的数据库 SQLite3)
(1)生成迁移文件,命令python manage.py makemigrations,本步骤生成数据库描述文件,会在该app下建立 migrations目录,记录models.py的全部更改记录,不会实际应用到数据库文件上
(base) D:\YYL\Mine\Study\Django_Mine>python manage.py makemigrations
Migrations for 'auth':
D:\worksoftware\Anaconda3.2\lib\site-packages\django\contrib\auth\migrations\0012_auto_20210322_1012.py
- Alter field name on group
Migrations for 'my_app':
my_app\migrations\0001_initial.py
- Create model Myapp_students
(2)将models变化应用到数据库上,命令python manage.py migrate,本步骤将models中记录的变化应用到数据库上
(base) D:\YYL\Mine\Study\Django_Mine>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, my_app, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_auto_20210322_1012... OK
Applying my_app.0001_initial... OK
Applying sessions.0001_initial... OK
4.QuerySet API
见Django学习笔记——模型,数据库(二)——QuerySet API