查询一般是使用filter、exculde及get三个方法实现,我们可以在调用这些方法的时候传递不同的参数来实现查询的需求,在get层面,这些查询条件都是使用field+_+condition的方式使用的,会介绍常用的查询条件:
1.exact(精确的):
精确的提供条件,如果提供的是一个None,那么在SQL层面是被解释为NULL,示例代码如下:
article = Article.objects.get(id_exact=14)
article = Article.objects.get(id_exact=None)
解释为SQL语句就是:
select ... from article where id=14;
select ... from article where id is NULL;
举例说明:
models.py文件中示例代码如下:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content)
class Meta:
db_table = 'article'
views.py文件中示例代码如下:
from .models import Article
from django.http import HttpResponse
def index(request):
# 1.插入一条记录
# article = Article(title="Hello", content="你好")
# article.save()
# 2.使用field__exact进行查询记录
# 使用 filter()方法得到的记录为QuerySet类型的
article = Article.objects.filter(id=1)
print(article)
# 打印出查询语句的原生SQL语句
print(article.query)
# # 3.使用get()方法或得的对象为article
# article = Article.objects.get(id__exact=1)
# print(article)
return HttpResponse("success")
查询结果如下所示:
使用exact()函数进行查询,但是这种查询方式,是不分大小写的。
from .models import Article
from django.http import HttpResponse
def index(request):
# 4.查询title为hello的记录,在windows系统中,数据库中的排序规则(collation)无论是什么,都不会区分大小写
# 在Linux系统中,数据库的排序规则(collation)为utf8_bin时,是可以区分大小写的。
article = Article.objects.filter(title__exact='hello')
print(article)
return HttpResponse("success")
数据库中的记录如下所示 :
输出查询结果:
使用exact进行查询的时候,将article = Article.objects.filter(id__exact=1),打印出原生SQL语句为,SELECT article
.id
, article
.title
, article
.content
FROM article
WHERE article
.id
= 1。
2.iexact:
忽略大小写的精确查询,实例代码如下:
from .models import Article
from django.http import HttpResponse
def index(request):
# 4.查询title为hello的记录
article = Article.objects.filter(title__iexact='hello')
print(article)
print(article.query)
return HttpResponse("success")
打印出原生SQL语句为,
SELECT article
.id
, article
.title
, article
.content
FROM article
WHERE article
.title
LIKE hello。一定要注意,LIKE,而不是=,如果查询条件为%hello%的话,此时就会返回所有带有hello的article。LIKE和=,大部分是等价的,只有少数情况下不等价。
exact在底层会被翻译成 sql语句中=,而iexact则会被翻译成LIKE。
其实,“field__exact=xxx等价于field=xxx”,因此,我们直接使用“field=xxx就可以了。”同时,因为大部分情况下,‘exact’和‘iexact’又是等价的,因此我们就可以直接使用field=xxx。
注意:如果想要使用query属性打印出,查询语句的原生SQL语句的话,对象必须是QuerySet类型,而不能是模型,模型没有query属性。并且会报错:
比如,使用get()方法得到的就是ORM模型,而filter()得到的就是QuerySet类型的数据。
总结:1.QuerySet.query: 'query’可以用来查看这个“ORM”模型被翻译成的“SQL”语句,但是“query”只能用在“QuerySet”对象上,而不能用在普通的“ORM”模型上。
2. 如果是使用get()方法获得的数据,那么就不能使用“query”,因为“get”返回的是满足条件的ORM模型,而不是“QuerySet”,如果是使用“filter”等可以返回“QuerySet”的方法查询的,那么就可以使用“query”