开始

python manage.py runserver # 启动服务器

数据库

# 生成迁移文件
python manage.py makemigrations polls
# 迁移
python manage.py migrate

API

# 内置shell
python manage.py shell

>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
# 增
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2022, 7, 12, 14, 17, 48, 894694, tzinfo=datetime.timezone.utc)
# 改
>>> q.question_text = "What' up?"
>>> q.save()
# 查
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
>>> Question.objects.get(pk=1) # pk 主键缩写
<Question: What's up?>
# Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API. 获取外键另一边
>>> q.choice_set.all()
<QuerySet []>
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
<Question: What' up?>
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
# 删
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
# Use double underscores to separate relationships.
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>]>

管理页面

# 管理员
python manage.py createsuperuser
# admin.py
from .models import Question
admin.site.register(Question) # 太秀了,直接后台操作数据库

模板