django model 条件过滤 queryset.filter(**condtions)用法详解

1、下述代码查询model对应数据库中日期等于2018-05-22的数据:

queryset = model.objects.all() 
condtions: {'date': '2018-05-22'}
query_res = queryset.filter(**condtions)

2、下述代码查询model对应数据库中日期小于2018-05-22的数据:

queryset = model.objects.all() 
condtions: {'date__lt': '2018-05-22'}
query_res = queryset.filter(**condtions)

3.总结:条件选取querySet的时候,filter表示=,exclude表示!=。

querySet.distinct() 去重复

__exact 精确等于 like 'aaa'
__iexact 精确等于 忽略大小写 ilike 'aaa'
__contains 包含 like '%aaa%'
__icontains 包含 忽略大小写 ilike '%aaa%',但是对于sqlite来说,contains的作用效果等同于icontains。
__gt 大于
__gte 大于等于
__lt 小于
__lte 小于等于
__in 存在于一个list范围内
__startswith 以...开头
__istartswith 以...开头 忽略大小写
__endswith 以...结尾
__iendswith 以...结尾,忽略大小写
__range 在...范围内
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
__isnull=True/False

如果参数是字典,如

condtions: {'date__lt': '2018-05-22','status': '未支付','name__exact': 'yangxia'}
Entry.objects.filter(**condtions)相当于 Entry.objects.filter(date__lt= '2018-05-22',status='未支付',name__exact='yangxia')

翻译成sql语句是

select * from Entry.objects where date<='2018-05-22' and status='未支付' and name like 'yangxia'

filter例子:

>> q1 = Entry.objects.filter(headline__startswith="What")
>> q2= q1.filter(pub_date__gte=datetime.date.today())
>>> q3= q.filter(pub_date__lte=datetime.date.today())

exclude例子:

>>> q1 = q.exclude(body_text__icontains="food")

>> q2 = q1.exclude(pub_date__gte=datetime.date.today())

补充知识:如何使用django的objects.filter()方法匹配多个关键字

介绍:

今天在使用django的时候忽然想用到,如何匹配多个关键字的操作,我们知道django有一个objects.filter()方法,我们可以通过如下一句代码实现匹配数据库中title包含key关键词的文章名称。

table.objects.filter(title__contains=key)

问题:

但是我的需求是我不仅仅只需要匹配出一个关键字的文章而是多个关键字的文章,那么我们该如何使用django的objects.filter()?

table.objects.filter(title__contains=key1)+.objects.filter(title__contains=key2)+....?

解决:

我们都知道在正常的sql语句中如果我们需要匹配多个关键字的title可以这样做

select title from data where title regexp 'key1|key2'
select title from data where title like '%key1%' or like '%key2%'

以上的两种sql语句都是选择出title属性中存在key1和key2的所有文章,那么django是不是也会有一种方法匹配多个关键字呢?当然有就是下面的代码

from django.db.models import Q
table.object.filter(Q(title__startswith='key1') | Q(title__startswith='key2'))

首先导入django的Q方法然后在filter中添加对应的匹配即可

以上这篇django model 条件过滤 queryset.filter(**condtions)用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。