获取 QuerySet
ORM 基于 QuerySet 工作。我们可以对从数据库中获得的 QuerySet 使用若干种过滤器进行结果的限制。比如说 get()
方法。举个🌰就是 User.objects.get()
。
all_posts = Post.objects.all()
Using the filter() method
To filter a QuerySet, you can use the filter() method of the manager. For example, we can retrieve all posts published in the year 2015 using the following QuerySet:
Post.objects.filter(publish__year=2015)
You can also filter by multiple fields. For example, we can retrieve all posts published in 2015 by the author with the username admin:
Post.objects.filter(publish__year=2015, author__username='admin')
This equals to building the same QuerySet chaining multiple filters:
Post.objects.filter(publish__year=2015)\
filter(author__username='admin')
Using exclude()
You can exclude certain results from your QuerySet using the exclude() method of the manager. For example, we can retrieve all posts published in 2015 whose titles don't start by Why:
.exclude(title__startswith='Why')```
# Using order_by()
You can order results by different elds using the order_by() method of the manager. For example, you can retrieve all objects ordered by their title:
``` Post.objects.order_by('title')```
Ascending order is implied. You can indicate descending order with a negative sign pre x, like this:
Post.objects.order_by('-title')
# Deleting objects
If you want to delete an object, you can do it from the object instance:
post = Post.objects.get(id=1)
post.delete()
# QuerySet 什么时候 evaluate?
我们可以对 QuerySet 进行多次的过滤操作,这个过程直到 QuerySet 被 evaluate 时才会触及数据库。而 evaluate QuerySet 只有下面几种情况:
• 首次迭代时 The first time you iterate over them
• 对其进行切片时 When you slice them. for instance: `Post.objects.all()[:3]`
• pickle 或者 cache 时 When you pickle or cache them
• 调用 `repr()` 或者 `len()` 时 When you call repr() or len() on them
• 显式调用 `list()` 时 When you explicitly call list()on them
• 在语句中测试时 When you test it in a statement such as `bool()`, `or` , `and`, or `if`
网友评论