过滤器组合:
Q(id__ge=10),Q(pid__ge=10) (id > 10) AND (pid > 10)
Q(id__ge=10)|Q(pid__ge=10) (id > 10) OR (pid > 10)
条件搜索:
order_by() 排序
distinct() 消除重复结果
id__gt=10 id > 10
id__gte=10 id >= 10
id__lt=10 id < 10
id__lte=10 id <= 10
id__startswith='xx' id like 'xx%'
id__istartswith='xx' id ILIKE 'xx%'
id__endswith='xx' id LIKE '%xx'
id__iendswith='xx' id ILIKE '%xx'
id__exact='xx' id LIKE 'xx'
id__iexact='xx' id ILIKE 'xx'
id__contains='xx' id LIKE '%xx%'
id__icontains='xx' id ILIKE '%xx%'
id__in=[1, 3, 4] id IN (1, 3, 4)
id__exact=14 id = 14
id__exact=None id IS NULL
id__isnull=Ture id IS NULL
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
id__range=(start_date, end_date) id BETWEEN '2005-01-01' and '2005-03-31';
id__year=2009 EXTRACT('year' FROM id) = '2009'
id__iregex=r'^(an?|the) +' id REGEXP '^(an?|the) +'
返回结果数量限制:
Entry.objects.all()[:5] LIMIT 5
Entry.objects.all()[5:10] OFFSET 5 LIMIT 5
Entry.objects.all()[:10:2] step 2
Entry.objects.order_by('headline')[0] LIMIT 1
数据操作:
.delete() 删除
.save() 更新
.count() 结果数量
容错处理:
from django.core.exceptions import ObjectDoesNotExist
try:
e = Entry.objects.get(id=3)
except ObjectDoesNotExist:
print "Either the entry doesn't exist."
try:
obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
obj.save()