django 从零开始系列二 数据库及模型

1. 数据库配置

mysite/settings.py 文件中, 数据库配置如下
在这里插入图片描述
常见的engine :

  • django.db.backends.sqlite3
  • django.db.backends.postgresql
  • django.db.backends.mysql
  • django.db.backends.oracle

开启一个数据库
python manage.py migrate

mysite/settings.py 中的 Installed_apps 配置了 django 中的应用
在这里插入图片描述

  • django.contrib.admin – 管理员站点。
  • django.contrib.auth – 认证授权系统。
  • django.contrib.contenttypes – 内容类型框架。
  • django.contrib.sessions – 会话框架。
  • django.contrib.messages – 消息框架。
  • django.contrib.staticfiles – 管理静态文件的框架。

2. 创建模型

polls/models.py:

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)

模型都继承自 models.Model 类, 每个模型内有若干变量, 他们都是一个 Field 实例
在这里插入图片描述
在源码中我们可以看到, Field 为其他类的基类, 我们新写入的代码中, 可以理解为, Question或Choice 类为表名, 变量为字段名, 而 choice类中 question变量为ForeignKey, 就是数据库中的外键约束, 诸如此类, django 中于数据库关联的类都很容易联想得到


3. 激活模型

将polls 这个应用安装到项目里, 需要在配置类中添加如下代码

mysite/settings:
在这里插入图片描述

添加后, 执行
python manage.py makemigrations polls
在这里插入图片描述

执行命令后, 在 polls/migrations/0001_initial.py 可以看到模型的迁移数据
在这里插入图片描述

执行以下命令, 可以将存储的模型转换为 sql
python manage.py sqlmigrate polls 0001
在这里插入图片描述

再次运行 migrate 命令,在数据库里创建新定义的模型的数据表
在这里插入图片描述

4. django shell api

修改 polls/models.py 文件

from django.db import models
from django.utils import timezone
import datetime

# Create your models here.
class Question(models.Model):
  question_text = models.CharField(max_length=200)
   pub_date = models.DateTimeField('date published')

   def __str__(self) -> str:
       return self.question_text

   def was_published_recently(self):
       return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
   question = models.ForeignKey(Question, on_delete=models.CASCADE)
   choice_text = models.CharField(max_length=200)
   votes = models.IntegerField(default=0)

   def __str__(self):
       return self.choice_text

打开交互式命令行
python .\manage.py shell

>In [1]: from polls.models import Choice, Question

In [2]: Question.objects.all()
Out[2]: <QuerySet []>

In [3]: from django.utilsils import timezone
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-3-0d7c9ed602bf> in <module>
----> 1 from django.utilsils import timezone

ModuleNotFoundError: No module named 'django.utilsils'

In [4]: from django.utils import timezone

In [5]: q = Question(question_text="What's new?", pub_date=timezone.now())

In [6]: q.save()

In [7]: q.id
Out[7]: 1

In [8]: q.question_text
Out[8]: "What's new?"

In [9]: q.pub_date
Out[9]: datetime.datetime(2021, 3, 7, 13, 9, 25, 230935, tzinfo=<UTC>)

In [10]: Question.objects.all()
Out[10]: <QuerySet [<Question: Question object (1)>]>

>In [1]: from polls.models import Choice, Question

In [2]: Question.objects.all()
Out[2]: <QuerySet [<Question: What's new?>]>

In [3]: Question.objects.filter(id=1)
Out[3]: <QuerySet [<Question: What's new?>]>

In [4]: Question.objects.filter(question_text__startswith='What')
Out[4]: <QuerySet [<Question: What's new?>]>

In [5]: from django.utils import timezone

In [6]: current_year = timezone.now().year

In [7]: Question.objects.get(pub_date__year=current_year)
Out[7]: <Question: What's new?>

In [8]: Question.objects.get(id=2)
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
      ...
      
In [9]: q = Question.objects.get(pk=1)   **pk的含义是 primarykey**

In [10]: q.was_published_recently()
Out[10]: True

In [13]: q.question_text
Out[13]: "What's new?"

In [14]: q.choice_set.all()
Out[14]: <QuerySet []>

In [15]: q.choice_set.create(choice_text="this is first", votes=10)
Out[15]: <Choice: this is first>

In [16]: c = q.choice_set.create(choice_text="create from questionObj", votes=5)

In [17]: c.question
Out[17]: <Question: What's new?>

In [18]: q.choice_set.all()
Out[18]: <QuerySet [<Choice: this is first>, <Choice: create from questionObj>]>

In [19]: q.choice_set.count()
Out[19]: 2

In [20]: Choice.objects.filter(question__pub_date__year=current_year)
Out[20]: <QuerySet [<Choice: this is first>, <Choice: create from questionObj>]>

In [21]: Choice.objects.filter()
Out[21]: <QuerySet [<Choice: this is first>, <Choice: create from questionObj>]>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值