Django 1.0 中文文档-----查询方法参考

查询API参考

 

这篇文档详细描述了QuerySet API,是以现有的模型资料和数据库查询知道为基础,所以你在这之前需要阅读和理解这些文档。

在这篇参考中,我们用现有的weblog例子。

 

当QuerySets被求值

 

在内部,QuerySet被构造,过滤,裁切,分发,没有实际接触数据库直到被求值的时候。

你可以通过下面方法对QuerySet 求值

 

  • 跌送. QuerySet 是可跌送的, 并且首先执行数据库查询。例如, 这个会打印数据库里所有entries 的 headline
Python代码 
  1. for e in Entry.objects.all():  
  2.     print e.headline  
 
  • 切片. 像说的那样限制QuerySets, QuerySet 可以被切片, 用Python的 array-slicing 语法. 通常切段 QuerySet会返回另一个QuerySet, 但是Django会执行数据库查询当你用 "step"切片参数语法.
  • 序列化/缓存. 看下面的部分,详细介绍了当序列化 QuerySets涉及到的东西.Queryset结果从数据库里读取的重要
  • repr(). 当调用repr()时候QuerySet会被求值. 这是为了方便Python的交互解释, 因此当执行API交互时,你会立即看到结果
  • len(). 当调用len()时候QuerySet会被求值. 如你所预计的,这会返回queryset数量.
  • list(). 强制求值
    例如
    Python代码 
    1. 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

Python代码 
  1. Entry.objects.exclude(pub_date__gt=datetime.date(200513), headline='Hello')  

转化为SQL

Sql代码 
  1. SELECT ...  
  2. WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')  
Python代码 
  1. Entry.objects.exclude(pub_date__gt=datetime.date(200513)).exclude(headline='Hello')  

 转化为SQL

Sql代码 
  1. SELECT ...  
  2. WHERE NOT pub_date > '2005-1-3'  
  3. OR NOT headline = 'Hello'  
 

这个例子排除了所有pub_date大于 '2005-1-3' 或 headline 为 "hello" 的结果

 

 

order_by(*fields)

 

排序 Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

前面带 “-” 为降序

 

 

 

reverse()

 

 

 

将查询结果排序反转

 

 

distinct()

 

去重复

 

 

values(*fields)

 

 

把查询结果转化为字典列表取代model集合

 

 

 

 

Python代码 
  1. # This list contains a Blog object.  
  2. >>> Blog.objects.filter(name__startswith='Beatles')  
  3. [<Blog: Beatles Blog>]  
  4.   
  5. # This list contains a dictionary.  
  6. >>> Blog.objects.filter(name__startswith='Beatles').values()  
  7. [{'id'1'name''Beatles Blog''tagline''All the latest Beatles news.'}]  
 

同样也可以指定结果字段名

 

Python代码 
  1. >>> Blog.objects.values()  
  2. [{'id'1'name''Beatles Blog''tagline''All the latest Beatles news.'}],  
  3. >>> Blog.objects.values('id''name')  
  4. [{'id'1'name''Beatles Blog'}]  

 

values_list(*fields)

将查询结果集的model转化为元组

Python代码 
  1. >>> Entry.objects.values_list('id''headline')  
  2. [(1, u'First entry'), ...]  
  3.   
  4. >>> Entry.objects.values_list('id').order_by('id')  
  5. [(1,), (2,), (3,), ...]  
  6.   
  7. >>> Entry.objects.values_list('id', flat=True).order_by('id')  
  8. [123, ...]  
 
all()

取所有结果

 

select_related()

取关联数据,可设置关联数据的深度,如果不设置,关联数据为延迟加载方式读取。

 

Python代码 
  1. # Hits the database.  
  2. e = Entry.objects.get(id=5)  
  3.   
  4. # Hits the database again to get the related Blog object.  
  5. b = e.blog  
  6.   
  7.   
  8. # Hits the database.  
  9. e = Entry.objects.select_related().get(id=5)  
  10.   
  11. # Doesn't hit the database, because e.blog has been prepopulated  
  12. # in the previous query.  
  13. b = e.blog  
  14.   
  15.   
  16. class City(models.Model):  
  17.     # ...  
  18.   
  19. class Person(models.Model):  
  20.     # ...  
  21.     hometown = models.ForeignKey(City)  
  22.   
  23. class Book(models.Model):  
  24.     # ...  
  25.     author = models.ForeignKey(Person)  
  26.   
  27.   
  28. b = Book.objects.select_related().get(id=4)  
  29. p = b.author         # Doesn't hit the database.  
  30. c = p.hometown       # Doesn't hit the database.  
  31.   
  32. b = Book.objects.get(id=4# No select_related() in this example.  
  33. p = b.author         # Hits the database.  
  34. c = p.hometown       # Hits the database.  
 
extra(select=None, where=None, params=None, tables=None, order_by=None,select_params=None

扩展查询

 

有时候DJANGO的查询API不能方便的设置查询条件,提供了另外的扩展查询方法extra

select

Python代码 
  1. Entry.objects.extra(select={'is_recent'"pub_date > '2006-01-01'"})  
 
Python代码 
  1. Blog.objects.extra(  
  2.     select={  
  3.         'entry_count''SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'  
  4.     },  
  5. )  

 

Python代码 
  1. Blog.objects.extra(  
  2.     select=SortedDict([('a''%s'), ('b''%s')]),  
  3.     select_params=('one''two'))  

 

where tables
Python代码 
  1. Entry.objects.extra(where=['id IN (3, 4, 5, 20)'])  

order_by

 

Python代码 
  1. q = Entry.objects.extra(select={'is_recent'"pub_date > '2006-01-01'"})  
  2. q = q.extra(order_by = ['-is_recent'])  

 

params

 

Python代码 
  1. Entry.objects.extra(where=['headline=%s'], params=['Lennon'])  
 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值