settings.py 文件前,先设置 TIME_ZONE 为你自己时区。
Django 的自带应用:
django.contrib.admin -- 管理员站点, 你很快就会使用它。
django.contrib.auth -- 认证授权系统。
django.contrib.contenttypes -- 内容类型框架。
django.contrib.sessions -- 会话框架。
django.contrib.messages -- 消息框架。
django.contrib.staticfiles -- 管理静态文件的框架。
默认开启的某些应用需要至少一个数据表
python manage.py migrate
创建模型
Django 支持所有常用的数据库关系:多对一、多对多和一对一。
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200) #字符字段
pub_date = models.DateTimeField('date published') #日期时间字段
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
激活模型
mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
更新数据(迁移)生成迁移文件
python manage.py makemigrations polls
返回对应的 SQL
python manage.py sqlmigrate polls 0001
检查问题
python manage.py check
注意点:
输出的内容和你使用的数据库有关,上面的输出示例使用的是 PostgreSQL。
数据库的表名是由应用名(polls)和模型名的小写形式(question 和 choice)连接而来。
主键(IDs)会被自动创建。
默认的,Django 会在外键字段名后追加字符串 “_id” 。
外键关系由 FOREIGN KEY生成。
生成的 SQL语句是为你所用的数据库定制的,所以那些和数据库有关的字段类型,比如 auto_increment (MySQL)、 serial(PostgreSQL)和 integer primary key autoincrement (SQLite),Django会帮你自动处理。
这个 sqlmigrate命令并没有真正在你的数据库中的执行迁移 - 它只是把命令输出到屏幕上,让你看看 Django 认为需要执行哪些 SQL 语句。
应用数据库迁移
python manage.py migrate
database API
python manage.py shell
>>> from polls.models import Choice, Question
>>> Question.objects.all()
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
>>> q.question_text
>>> q.pub_date
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
models.py
from django.db import models
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Python 交互式命令行
python manage.py shell
>>> from polls.models import Choice, Question
>>> Question.objects.all()
>>> Question.objects.filter(id=1)
>>> Question.objects.filter(question_text__startswith='What')
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
>>> Question.objects.get(pk=1)
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
>>> q.choice_set.create(choice_text='Not much', votes=0)
>>> q.choice_set.create(choice_text='The sky', votes=0)
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
>>> q.choice_set.all()
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
Django 管理页面
创建管理页面的用户
python manage.py createsuperuser
管理页面中加入应用(admin)
from django.contrib import admin
from .models import Question
admin.site.register(Question)