models
創(chuàng)建模型:
- 打開supporter/models.py
- 添加模型類:
Article
class Article(models.Model):
title = models.CharField(max_length=32, default='title')
content = models.CharField(max_length=255, null=True)
創(chuàng)建數(shù)據(jù)庫遷移:
- 執(zhí)行命令:
python manage.py makemigrations supporter
- 看到如下結(jié)果:
Migrations for 'supporter':
supporter\migrations\0001_initial.py:
- Create model Article
- 執(zhí)行命令:
python manage.py migrate
- 看到如下結(jié)果:
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
==完成遷移==
完成遷移后續(xù):
- 完成遷移后赁炎,會在對應(yīng)的應(yīng)用目錄下migrations文件夾下創(chuàng)建遷移執(zhí)行文件,例如:
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)),
],
),
]
- 執(zhí)行命令:
python manage.py sqlmigrate supporter 0001
可以查看具體執(zhí)行的SQL語句 - 結(jié)果如下:
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;
- 數(shù)據(jù)庫文件存放地址:
項目根目錄/db.sqllite3
,沒有用戶名和密碼
讀取數(shù)據(jù)
- views中潜腻,引入模型:
from . import models
- 根據(jù)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>