官方文档
https://docs.djangoproject.com/zh-hans/4.1/intro/tutorial02/
模型设计哲学
一个模型就是单个定义你的数据的信息源。模型中包含了不可缺少的数据区域和你存储数据的行为。Django 遵循 DRY 原则。目的就是定义你的数据模型要在一位置上,而且自动从该位置推导一些事情。
案例中的模型
在这个投票应用中,需要创建两个模型:问题 Question 和选项 Choice。Question 模型包括问题描述和发布时间。Choice 模型有两个字段,选项描述和当前得票数。每个选项属于一个问题。
这些概念可以通过一个 Python 类来描述。按照下面的例子来编辑 polls/models.py 文件:
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('发布时间')
class Choice(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
迁移到数据库(manage.py makemigrations 、migrate)
这个涉及的原理很多,作为食用主义者,记住这三步操作就可以了:
1、编辑 models.py 文件,改变模型。(检查 python manage.py check 检查项目中的问题)
2、运行 python manage.py makemigrations 为模型的改变生成迁移文件。
3、运行 python manage.py migrate 来应用数据库迁移。
为方便运行这些命令而不至反复复制绝对路径,最终我妥协了,还是污染一下我的操作系统环境:
这样就可以愉快使用相对路径来执行命令了:
代码添加数据到数据库中
下面照着官方的例子熟悉一下Django操作数据库和类的方法:
python manage.py shell
>>> from polls.models import Choice, Question # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
更多关于数据库和模型的操作可以看一下两个文档
https://docs.djangoproject.com/zh-hans/4.1/topics/db/queries/
https://docs.djangoproject.com/zh-hans/4.1/ref/models/relations/
这样,我们就完成了模型和数据库的创建