filter(**kwargs)
返回一个与参数匹配的QuerySet,相当于等于(=)
exclude(**kwargs)
返回一个与参数不匹配的QuerySet,相当于不等于(!=)
Model.objects.filter(create_time__year=2019)
等同于SQL语句 select * from model where create_time_year='2019'
Model.objects.filter(
name__startswith='张'
).exclude(
id__gte=188
).filter(
create_time__gte=datetime(2018,10,10)
)
等同于
select * from model where name like '张%' and id>=188 and create_time>'2018-10-10'
QuerySet1 = Model.objects.filter(name__startswith='张')
QuerySet2 = QuerySet1.exclude(id__gte=188)
QuerySet3 = QuerySet1.filter(create_time__gte=datetime(2018,10,10))
这种方法的好处是可以对所有查询属性可以重用。
而且QuerySet是延迟属性,只有当使用到数据库时,才会去访问数据库
obj = Model.objects.all()[:5]
obj = Model.objects.all()[5:10]
obj = Model.objects.all()[0:10:2]
obj = Model.objects.order_by('create_time')[0]
obj = Model.objects.filter(create_time__lte='2018,10,10')
SELECT * FROM model WHERE create_time<=2018-10-10;
obj = Model.objects.get(name__iexact='kre_kre')
obj = Model.objects.filter(name__contains='王')
SELECT * FROM model WHERE name LIKE '%王%'
obj = Model.objects.filter(second_table__author_name__isnull=True)
obj = Model.objects.filter(second_table__author_name__isnull=False,second_table__author_name__is)
obj = Model.objects.get(id__exact=14)
,obj = Model.objects.get(id=14)
,obj = Model.objects.get(pk=14)
select * from model where id=14;
obj = Model.objects.filter(pk__in=[1,3,5,7,9])
select * from model where id in {1,3,5,7,9};
Model.objects.filter(name__contains='%')
select * from model where name like '%\%%';
[e.id for e in Model.objects.all()]
query_set = Model.objects.all()
[e.id for e in query_set]
from django.db.model import Q
from datetime import datetime
obj = Model.objects.filter(Q(question__startswith='who')|Q(question__startswith='what'))
等同于:select * from model where question like 'who%' or question like 'what%'
query_set = Model.objects.filter(
Q(create_time__gte=datetime(2018,10,10)) | Q(
create_time__lte=datetime(2019,10,10)),
name__startswith='张'
)
等同于:select * from model where name like '张%' and create_time >= '2018-10-10' and create_time <= '2019-10-10';
亦可写为:
query_set = Model.objects.filter(
name__startswith='张',
Q(create_time__range(
datetime(2018,10,10),datetime(2019,10,10)
))
)
from django.db.model import F
obj = Model.objects.filter(girl_num__gt=F('boy_num'))
object = Model.objects.filter(girl_num__gte=F('boy_num')+20)
obj = Model.objects.filter(create_time__lt=F('create_at')+timedelta(days=5))
2019-08-08