Django的使用--MySql数据库

1.配置Django中MySql

提前在MySql数据库中创建要进行测试的新数据库djangobase
Django中默认使用SQLite作为默认数据库,要使用其他数据库需要更改mysite/setting.py中的DATABASES配置

在项目mysite中找到配置文件setting.py
更改配置文件中的DATABASE

原本的SQLite数据库配置:

DATABASES = {
	 'default': {
     'ENGINE': 'django.db.backends.sqlite3',
     'NAME': BASE_DIR / 'db.sqlite3',
   }
}

更改之后
MySql数据库的配置:

import pymysql

pymysql.install_as_MySQLdb()
DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.mysql'	# 数据库引擎
		'NAME': '数据库名'	# 填入数据库名称
		'USER': 'root'	# 填入用户名
		'PASSWARD' : '密码' # 填入密码
		'HOST': 'localhost' # 填入IP
		'PORT': '3306'	# 端口
	}
}

首先使用语句,检查是否有对models.py(模型文件)的修改
python manage.py makemigrations

如果有则会在相应的应用(之前的(polls))中创建一个数据脚本,作为模型的迁移数据脚本,储存在应用目录下的migrations中(演示时会讲述)

再使用:
python manage.py migrate

migrate会检查 INSTALLED_APPS 里面的配置,为每个应用创建需要的数据表。

检查对应djangobase数据库时就可以发现多了以下表格
说明导入和配置成功
在这里插入图片描述

2.创建数据库模型

我们拿之前设计的polls来
在应用polls中
编辑polls/models.py文件:

# pools/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)

应用polls的模型文件models.py编写完成之后,在终端输入:
python manage.py makemigrations polls
makemigrations 会检查对polls应用的模型文件models.py的修改,会把修改的部分储存成一个迁移数据脚本
在这里插入图片描述
迁移数据脚本储存在:polls/migrations/0001_initial.py
也可以使用python manage.py sqlmigrate polls 0001查阅0001数据脚本

迁移数据脚本生成之后,并没有直接作用到本地数据库中,还需要使用migrate语句进行数据迁移:
python manage.py migrate
在这里插入图片描述
之后检查我们对应的“djangobase”数据库的“

在这里插入图片描述
choicequestion表创建完成

上述表格都没有插入主键(Primary key),Django会自动给表生成一个主键id
Question:
在这里插入图片描述
Choice:
在这里插入图片描述
设置主键只需要在字段最后加一个参数primary_key = True

3.初试Shell

首先需要进入Shell的操作界面
进入终端CMD命令行后,输入以下语句:
python manage.py shell

增加
在Question表中增加一行
question_text值为"What’s new?"
pub_date值为timezone.now()
解释:
timezone.now() —— 显示当前时间
需要添加库from django.utils import timezone

q = Question(question_text="What's new?", pub_date=timezone.now())	
#	在Question表中 “question_text”字段增加 “What's new”; "pub_date"字段增加"timezone.now"
# timezone.now()获取当前时间 
q.save()
# 保存数据	

查询

>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2021, 9, 22, 3, 27, 11, 394989, tzinfo=<UTC>)

字段更改
把==q==这一行的question_text列的值更改成"What’s up?"

>>> q.question_text = "What's up?"
>>> q.save()
# 保存数据,直接同步到本地数据库

显示库中所有数据
库.objects.all()
以下显示的是Question库中的数据

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

退出Shell模式:

exit()
Use exit() or Ctrl-Z plus Return to exit

3.1 给表格增加方法(在表格里创建自定义函数)

使用Question.objects.all()之后出现的<QuerySet [<Question: Question object (1)>]>
只能显示有多少个object,并不能显示细节
我们在polls/models.py在各表中使用__str__()方法来修复这个问题

Question表:

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

    # Django 自动生成的 admin 里也使用__str__()方法来表示对象
    # 在Shell中使用Question.objects.all()是返回__str__()方法中的返回值
    def __str__(self):
        return self.question_text

Choice表:

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

在表中制作了__str__()方法后,使用Question.object.all()得到的结果:

<QuerySet [<Question: What's up?>]>

查表的方法
Django提供了丰富的数据库查询API:
表.objects.filter()
从数据库中取得匹配的结果,返回一个列表

  1. 使用id查询:
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
  1. 使用开头字符查询:
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>

表.objects.get()
从数据库取得一个匹配的结果,返回一个对象

  1. 使用年份来查询:
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
  1. 使用id来查询:
>>> Question.objects.get(id=2)

查不到就会报错

  1. 查找主键pk=1(primary key)
>>> Question.objects.get(pk=1)
<Question: What's up?>
  1. 运用自定义函数,检查某个字段是否是最近才创建的:
    首先在models.py中Question表中添加自定义方法:
def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    # timezone.now() 减去 datetime.timedelta(days=1) 24小时
    # 得出昨天的当前时间

再在终端中调用它

 >>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
  1. 通过Question表来查对应的Choice表信息
    口诀:有外键用外键,没有外键用表名加_set

Question表:

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

Choice表:

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

具体查询方法:
Question表中没有设置外键,只能通过表+_set,查询对应Choice表对应的信息
通过问题question添加选项,由于问题表里没有外键,所以用他关联的表名加_set来查

>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
<QuerySet []>

Choice表设置了外键question,则可以通过外键来查询对应Question表中的信息

>>> c = q.choice_set.create(choice_text='Just hacking again',votes=0)
>>> c.question	# 使用question外键查询Question表中对应信息
<Question: What's up?>

查询Question一个键对应Choice里总的数据量:

>>> q.choice_set.count()
3
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

删除

>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {'polls.Choice': 1})
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值