Django_QuerySet

2018-07-23  本文已影响71人  dchang

QuerySet

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发布的条目以外的数据

>>> 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))
>>> 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 '%\%%';
>>> 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
>>> 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
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))
)
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
>>> 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()
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
设置pk为none,再次保存就会生成一个新的记录
blog.pk = None
blog.save() # blog.pk == 2

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) # 不查询数据库
如果 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 关系同 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
上一篇 下一篇

猜你喜欢

热点阅读