模板:
from django.db import models class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
category = models.ForeignKey('Category',on_delete=models.CASCADE,null=True)
create_time = models.DateTimeField(auto_now_add=True,null=True) # 保存时获取当前时间
class Meta:
db_table = 'article'
def __str__(self):
return "<Article: ID:%s,title:%s,content:%s>" % (self.id,self.title,self.content) class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
db_table = 'category'
视图导入:
from django.shortcuts import render
from .models import Article,Category
from django.http import HttpResponse
from datetime import datetime,time,date
from django.utils.timezone import make_aware def...
数据库内容:
- 使用filter返回QuerySet数据集类型,可调用方法.query;使用get返回一个模型时,不能使用该方法;
- QuerySet.query:‘query’可用来查看这个‘ORM’查询语句最终被翻译成的‘SQL’语句;
- exact/iexact:查找的与原内容完全相等时才能被找到,只是like与=的区别,多数情况下是一样的,可直接省略‘__exact’;
def index(requset):
article = Article.objects.filter(title__exact='三国演义')
article = Article.objects.filter(title__iexact='三国演义')
print(article.query)
print(type(article))
return HttpResponse('success')
# >>> SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` = 三国演义
# >>> SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE 三国演义
# <class 'django.db.models.query.QuerySet'> - contains/icontains:只要包含有查找的内容就能被找到;
def index1(request):
result = Article.objects.filter(title__contains='hello')
print(result.query)
return HttpResponse('success')
# 使用contains区分大小写,icontains不区分;
# SELECT `article`.`id`, `article`.`title`, `article`.`content` FROM `article` WHERE `article`.`title` LIKE BINARY %hello% - in:查找in中所包含的内容
def index2(requset):
# 1、查找id为1,2,3的文章
articles = Articel.objects.filter(id__in=[1,2,3])
for article in articles:
print(article) # 2、查找文章id为1,2,3的分类;'__id'可省略;article_in中的‘article’反向查询可用‘related_query_name’改名,
# 类似于‘related_name’的用法,改后仍需加‘__in’;
category = Category.objects.filter(articel__id__in=[1,2,3]) # 查找所有包含hello的分类
articles = Article.objects.filter(title__icontains='hello')
categorys = Category.objects.filter(article__in=articles)
for category in categorys:
print(category)
return HttpResponse('success') - gt/gte、lt/lte:大于/大于等于、小于/小于等于;(greater/lower than equal)
article = Article.objects.filter(id__gt=2)
# startswith/endswith:以什么开头或结尾,前面加‘i’表不区分大小写;
articles = Article.objects.filter(title__startswith='hello')
return HttpResponse('success') - range:需指定时间段,时间应标记为‘aware’时间。(make_aware(value,timezone=None,is_dst=None):没有传入时区时,将获取当前的时区:timezone = get_current_timezone();即获取settings.py中‘TIME_ZONE = 'Asia/Shanghai'’设置的时区;)
def index5(requset):
start_time = make_aware(datetime(year=2019,month=3,day=7,hour=15,minute=0,second=0))
end_time = make_aware(datetime(year=2019,month=3,day=7,hour=16,minute=0,second=0))
articles = Article.objects.filter(creat_time__range=(start_time,end_time))
print(articles.query)
print(articles)
return HttpResponse('success') - DATE:将create_time的datetime类型转换为DATE的类型;
def index6(request):
article = Article.objects.filter(create_time__date=date(year=2019,month=3,day=7))
print(article.query)
print(article)
return HttpResponse('success')# CONVERT_TZ:将时间从UTC的时区转换为Asia/Shanghai的时区;因MySQL本身不具备这些时区的信息,所以相当于
# 转换失败,需将具有该信息的文件拷贝进mysql中。
# 在官网https://dev.mysql.com/downloads/timezones.html中下载文件timezone_2018i_posix.zip - POSIX standard解压后拷贝覆盖
# 到:C:\ProgramData\MySQL\MySQL Server 5.7\Data\mysql 路径下(先将原文件保存);
# 后重启数据库,使用命令:set stop/start [mysql数据库名] 进行重启(可在服务中查看数据库名字);
# Linux或Mac中執行命令:mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -D mysql -u root -p 密码;(数据库,用户,密码)
# 错误输出:<QuerySet []>
# 正常输出:
# SELECT `article`.`id`, `article`.`title`, `article`.`content`, `article`.`category_id`, `article`.`create_time` FROM
# `article` WHERE DATE(CONVERT_TZ(`article`.`create_time`, 'UTC', 'Asia/Shanghai')) = 2019-03-07
# <QuerySet [<Article: <Article: ID:1,title:西游记,content:abc...>>,<Article: <Article: ID:2,title:三国演义,content:123...>>, <Article: <Article: ID:3,title:Hello world,content:xxx>>,<Article: <Article: ID:4,title:英文单词:hello,content:aaa>>, <Article: <Article: ID:5,title:红楼梦,content:aaa...>>]>def index7(request):
# 查找某个时间的数据,因秒(second)需精确到小数位,所以用range方法;
# article = Article.objects.filter(create_time__time=time(hour=15, minute=29, second=15))
start_time = time(hour=15,minute=29,second=15)
end_time = time(hour=15,minute=29,second=16)
article = Article.objects.filter(create_time__time__range=(start_time,end_time))
print(article)
return HttpResponse('success') - regex:使用正则表达式
def index8(request):
# regex 表示区分大小写
articles = Article.objects.filter(title__iregex=r"^hello")
print(articles)