Django_QuerySet

QuerySet

  • Retrieving all objects: 查询所有数据记录,SELECT *

    all_entries = Entry.objects.all() : returns a QuerySet of all the objects in the database.

  • Retrieving specific objects with filters,根据限定条件查询,SELECT ... WHERE...

    • filter(**kwargs): Returns a new QuerySet containing objects that match the given lookup parameters.

    • exclude(**kwargs): Returns a new QuerySet containing objects that do not match the given lookup parameters.

      Entry.objects.filter(pub_date__year=2006) == Entry.objects.all().filter(pub_date__year=2006)

  • Retrieving a single object with get()

    one_entry = Entry.objects.get(pk=1)

  • Limiting QuerySet: This is the equivalent of SQL's LIMIT and OFFSET clauses.

    Entry.objects.all()[:5] : first 5 objects (LIMIT 5):
    Entry.objects.all()[5:10] : the sixth through tenth objects (OFFSET 5 LIMIT 5):

  • Negative indexing id not support neither does slice with step like Entry.objects.all()[:10:2]

Field lookups

Entry.objects.filter(blog_id=4)
Entry.objects.get(headline__exact="Cat bites dog") == SELECT ... WHERE headline = 'Cat bites dog';
Blog.objects.get(id__exact=14) # Explicit form
Blog.objects.get(id=14) # __exact is implied
Blog.objects.get(name__iexact="beatles blog") => "Beatles Blog", "beatles blog", or even "BeAtlES blOG".
Entry.objects.get(headline__contains='Lennon')
startswith, endswith, istartswith, iendswith

Lookups that span relationships: 深入关系内查询

Entry.objects.filter(blog__name='Beatles Blog')
Blog.objects.filter(entry__headline__contains='Lennon')
Blog.objects.filter(entry__authors__name='Lennon')
Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) => 2条件的交集
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) => 2条件的并集

Suppose there is only one blog that had both entries containing "Lennon" and entries from 2008, but that none of the entries from 2008 contained "Lennon". The first query would not return any blogs, but the second query would return that one blog.
如果有一个blog,包含有条目,其中有的是包括 “Lennon”字段的,有的是2008之后发布的,但是没有哪个条目是同时包含2个条件的,所以针对第一个QuerySet,同时满足条件的条目并不存在,返回空的Set,但是第二Query,满足有包含Lennon和2008之后发表的blog是可以查询到的,所以返回该blog。

Blog.objects.exclude(
    entry__headline__contains='Lennon',
    entry__pub_date__year=2008,
)

以上表示 在Blog中去除headline包含Lennon或者2008发布的集合

Blog.objects.exclude(
    entry__in=Entry.objects.filter(
        headline__contains='Lennon',
        pub_date__year=2008,
    )
)

以上表示去除headline包括Lennon并且2008发布的条目以外的数据

  • Filters can reference fields on the model, 同一个model内的不同数据作比较,可以理解为在一句query内查询多个数据进行比较
>>> from django.db.models import F
>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks'))

>>> Entry.objects.filter(n_comments__gt=F('n_pingbacks') * 2)
>>> Entry.objects.filter(rating__lt=F('n_comments') + F('n_pingbacks'))
>>> Entry.objects.filter(authors__name=F('blog__name'))

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
  • The pk lookup shortcut
>>> Blog.objects.get(id__exact=14) # Explicit form
>>> Blog.objects.get(id=14) # __exact is implied
>>> Blog.objects.get(pk=14) # pk implies id__exact

# Get blogs entries with id 1, 4 and 7
>>> Blog.objects.filter(pk__in=[1,4,7])
# Get all blog entries with id > 14
>>> Blog.objects.filter(pk__gt=14)

>>> Entry.objects.filter(blog__id__exact=3) # Explicit form
>>> Entry.objects.filter(blog__id=3)        # __exact is implied
>>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact

>>> Entry.objects.filter(headline__contains='%')
>>> SELECT ... WHERE headline LIKE '%\%%';
  • Caching and QuerySets
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
>>> 以上会产生2次数据库请求

>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset]) # Evaluate the query set.
>>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation
>>> 如果已经遍历过一次QS,下一次则会使用cache
  • When QuerySets are not cached
>>> queryset = Entry.objects.all()
>>> print(queryset[5]) # Queries the database
>>> print(queryset[5]) # Queries the database again

>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset] # Queries the database
>>> print(queryset[5]) # Uses cache
>>> print(queryset[5]) # Uses cache
  • Complex lookups with Q objects
Q(question__startswith='Who') | Q(question__startswith='What') == WHERE question LIKE 'Who%' OR question LIKE 'What%'


Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
) ==>
SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')

如果有Q操作和关键字的操作,Q操作至前
1. ok
Poll.objects.get(
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    question__startswith='Who',
)
2. not valid
Poll.objects.get(
    question__startswith='Who',
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
  • Deleting objects
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
  • Deleting objects
>>> e.delete()
(1, {'weblog.Entry': 1})

Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})

默认会删除外键所关联的其他表的内容,ON DELETE CASCAD
b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()

delete只作用到queryset,所以删除全部就是以下方法
Entry.objects.all().delete()
  • Copying model instances
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
设置pk为none,再次保存就会生成一个新的记录
blog.pk = None
blog.save() # blog.pk == 2
  • Updating multiple objects at once

  • 对象的对应关系
    • One-To-Many 关系
    • 正向获取 父表 to 子表
e = Entry.objects.get(id=2)
e.blog # 返回通过外键关联的 blog 对象
#如果要更新 e 对象的 blog 属性
b = Blog.objects.get(id=3)
e.blog = b
e.save() # 执行根系操作,
 
one-to-many 关系在第一次使用后将会被缓存
e = Entry.objects.get(id=2)
print(e.blog) # 查询数据, 并将数据缓存
print(e.blog) # 不查询数据库, 之间中缓存中读取

使用 QuerySet 的 select_related() 方法时, 会将相应的 one-to-many 关系的对象都预先取出来并缓存, 在真正使用时就不会访问数据库
e = Entry.objects.select_related().get(id=2)
print(e.blog) # 不查询数据库
print(e.bong) # 不查询数据库
  • 反向获取 子表 to 父表
如果 model A 通过 ForeignKey字段 field 与 model B 想关联。 
B 对象可以通过 model Manager 去访问与之对应的所有的 A 对象。 
默认的, 这个 model Manage 名为 foo_set, 其中 foo 是拥有外键那个 model 名的小写, 即 a_set()
例: 通过 Blog 对象查询 Entry 对象:
    
# 查询与 Blog 对象 b 关联的所有 entry 对象
b = Blog.objects.get(pk=2)
b.entry_set.all()
 
# 查询与 Blog 对象 b 关联的 entry 对象中 headline 包含 'Lennon' 的
b.entry_set.filter(headline__contains='Lennon')

如果在定义 ForeignKey 字段时 通过 related_name 可以更改这个默认的 foo_set() Manage 方法。
例如: 将最顶部的 Entry Model 中的 blog 字段修改成如下:
blog = ForeignKey(Blog, related_name=’entries’), 上面的代码中的 entry_set 就可以都改成 entries
    
# 查询与 Blog 对象 b 关联的所有 entry 对象
b = Blog.objects.get(pk=2)
b.entries.all()
 
# 查询与 Blog 对象 b 关联的 entry 对象中 headline 包含 'Lennon' 的
b.entries.filter(headline__contains='Lennon')
  • One-To-One 关系
One-to-one 关系同 many-to-one 非常相似, API 用法与 many-to-one 的基本也基本一致

class EntryDetail(models.Model):
    entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
    details = models.TextField()

ed = EntryDetail.objects.get(pk=3)
en.entry # 返回与之对应的 Entry 对象

与 many-to-one 不同的是其反向查找, 如下:    
e = Entry.objects.get(pk=3)
# 取得与 Entry 对象对应的 EntryDetail 对象,
# 只需调用 EntryDetail 的小写 entrydetail 即可
e.entrydetail
 
#更新
e.entrydetail = ed2
e.save()
  • 通过关联对象查询
当查询过滤条件传入 filter 函数是,既可以使用整个对象,可以使用相应的对象值。
# Blog 对象 b 的 id = 5
Entry.objects.filter(blog=b) # 通过整个对象进行查询
Entry.objects.filter(blog=b.id) # 通过 b 的 id 属性查询
Entry.objects.filter(blog=5) # 直接用 id 值查询 hard code
  • end

你可能感兴趣的:(Django_QuerySet)