查询API参考
这篇文档详细描述了QuerySet API,是以现有的模型资料和数据库查询知道为基础,所以你在这之前需要阅读和理解这些文档。
在这篇参考中,我们用现有的weblog例子。
当QuerySets被求值
在内部,QuerySet被构造,过滤,裁切,分发,没有实际接触数据库直到被求值的时候。
你可以通过下面方法对QuerySet 求值
for e in Entry.objects.all(): print e.headline
entry_list = list(Entry.objects.all())
QuerySet API
尽管你通常不会手动创建一个,你会通过一个Manager,这个声明的QuerySet
class QuerySet ([ model=None ] )
通常当你要和QuerySet交互,你会用过滤链的方式,大多数 QuerySet 的方法都会返回一个新的QuerySet
QuerySet方法返回新的QuerySet
filter(**kwargs)
返回一个匹配查询参数后的新的QuerySet
exclude(**kwargs)
返回一个不匹配查询参数后的新的QuerySet
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
转化为SQL
SELECT ... WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
转化为SQL
SELECT ... WHERE NOT pub_date > '2005-1-3' OR NOT headline = 'Hello'
这个例子排除了所有pub_date大于 '2005-1-3' 或 headline 为 "hello" 的结果
排序 Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
前面带 “-” 为降序
将查询结果排序反转
去重复
把查询结果转化为字典列表取代model集合
# This list contains a Blog object. >>> Blog.objects.filter(name__startswith='Beatles') [<Blog: Beatles Blog>] # This list contains a dictionary. >>> Blog.objects.filter(name__startswith='Beatles').values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
同样也可以指定结果字段名
>>> Blog.objects.values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}], >>> Blog.objects.values('id', 'name') [{'id': 1, 'name': 'Beatles Blog'}]
将查询结果集的model转化为元组
>>> Entry.objects.values_list('id', 'headline') [(1, u'First entry'), ...] >>> Entry.objects.values_list('id').order_by('id') [(1,), (2,), (3,), ...] >>> Entry.objects.values_list('id', flat=True).order_by('id') [1, 2, 3, ...]
取所有结果
取关联数据,可设置关联数据的深度,如果不设置,关联数据为延迟加载方式读取。
# Hits the database. e = Entry.objects.get(id=5) # Hits the database again to get the related Blog object. b = e.blog # Hits the database. e = Entry.objects.select_related().get(id=5) # Doesn't hit the database, because e.blog has been prepopulated # in the previous query. b = e.blog class City(models.Model): # ... class Person(models.Model): # ... hometown = models.ForeignKey(City) class Book(models.Model): # ... author = models.ForeignKey(Person) b = Book.objects.select_related().get(id=4) p = b.author # Doesn't hit the database. c = p.hometown # Doesn't hit the database. b = Book.objects.get(id=4) # No select_related() in this example. p = b.author # Hits the database. c = p.hometown # Hits the database.
扩展查询
有时候DJANGO的查询API不能方便的设置查询条件,提供了另外的扩展查询方法extra
select
Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
Blog.objects.extra( select={ 'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id' }, )
Blog.objects.extra( select=SortedDict([('a', '%s'), ('b', '%s')]), select_params=('one', 'two'))
Entry.objects.extra(where=['id IN (3, 4, 5, 20)'])
order_by
q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"}) q = q.extra(order_by = ['-is_recent'])
params
Entry.objects.extra(where=['headline=%s'], params=['Lennon'])