models
创建模型:
- 打开supporter/models.py
- 添加模型类:
Article
class Article(models.Model):
title = models.CharField(max_length=32, default='title')
content = models.CharField(max_length=255, null=True)
创建数据库迁移:
- 执行命令:
python manage.py makemigrations supporter
- 看到如下结果:
Migrations for 'supporter':
supporter\migrations\0001_initial.py:
- Create model Article
- 执行命令:
python manage.py migrate
- 看到如下结果:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, supporter
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 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 sessions.0001_initial... OK
Applying supporter.0001_initial... OK
==完成迁移==
完成迁移后续:
- 完成迁移后,会在对应的应用目录下migrations文件夹下创建迁移执行文件,例如:
supporter/migrations/0001_initial.py
- 打开文件:
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2018-04-27 13:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='title', max_length=32)),
('content', models.CharField(max_length=255, null=True)),
],
),
]
- 执行命令:
python manage.py sqlmigrate supporter 0001
可以查看具体执行的SQL语句 - 结果如下:
BEGIN;
--
-- Create model Article
--
CREATE TABLE "supporter_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(32) NOT NULL, "content" varchar(255) NULL);
COMMIT;
- 数据库文件存放地址:
项目根目录/db.sqllite3
,没有用户名和密码
读取数据
- views中,引入模型:
from . import models
- 根据id读取:
article = models.Article.objects.get(pk=1)
- 传递试图:
return render(request=request, template_name='index.html', context={'data': article})
- 试图渲染:
<h1>title:" {{ data.title }} "</h1>
<h2>content:" {{ data.content }} "</h2>
网友评论