Django4.1从入门到精通——模型的创建

官方文档
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/

这样,我们就完成了模型和数据库的创建

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值