假设有一个模型
class Article(models.Model): title=models.CharField(max_length=50) content=models.TextField() class Meta: db_table=‘book‘
对于查询结果是结果集,即通过filter进行查询所得的对象来说,可通过query属性来查看django转换之后的原生sql语句
…… article=Article.objects.filter(title=‘Hello World‘) print(article.query) print(article) ……
查询结果为
exact:即相当于数据库底层的等号=
article=Article.objects.filter(title_exact=‘Hello World‘),即相当于数据库底层的select ··· from ··· where title=‘Hello World‘
iexact:即相当于数据库底层的like
article=Article.objects.filter(title__iexact=‘Hello World‘),即相当于数据库底层的select ··· from ··· where title like ‘Hello World‘
contains:大小写敏感的匹配查询,也是like,注意转换后查询条件的两侧都有%
article=Article.objects.filter(title__contains=‘Hello World‘),即相当于数据库底层的select ··· from ··· where title like ‘%Hello World%‘
icontains:大小写不敏感的匹配查询
article=Article.objects.filter(title__icontains=‘Hello World‘),即相当于数据库底层的select ··· from ··· where title like ‘%Hello World%‘
in:查询条件是否在给定的范围内,用小括号和中括号都可以
article=Article.objects.filter(id__in=(1,2,6,9)),即相当于数据库底层的select ··· from ··· where id in (1,2,6,9)
gt:大于
gte:大于等于
lt:小于
lte:小于等于
article=Article.objects.filter(id__gt=5),即相当于数据库底层的select ··· from ··· where id > 5
startswith:以指定某个字符串开始,大小写敏感
istartswith:以指定某个字符串开始,大小写不敏感
endswith:以指定某个字符串结束,大小写敏感
iendswith:以指定某个字符串结束,大小写不敏感
article=Article.objects.filter(title__startswith=‘Hello‘),即相当于数据库底层的select ··· from ··· where title like ‘Hello%‘
article=Article.objects.filter(title__endswith=‘Hello‘),即相当于数据库底层的select ··· from ··· where title like %‘Hello‘
range:在某个范围,即相当于between ··· and ···,用小括号和中括号都可以
article=Article.objects.filter(id__range=(1,6)),即相当于select ··· from ··· where id between 1 and 6
isnull:是否为空
article=Article.objects.filter(content__isnull=False),即相当于select ··· from ··· where content is not null
原文地址:https://www.cnblogs.com/Forever77/p/10165158.html