Django ORM 的基石 —— QuerySet

獲取 QuerySet

ORM 基于 QuerySet 工作。我們可以對從數(shù)據(jù)庫中獲得的 QuerySet 使用若干種過濾器進行結(jié)果的限制。比如說 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 時才會觸及數(shù)據(jù)庫。而 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
? 調(diào)用 `repr()` 或者 `len()` 時 When you call repr() or len() on them
? 顯式調(diào)用 `list()` 時 When you explicitly call list()on them
? 在語句中測試時 When you test it in a statement such as `bool()`, `or` , `and`, or `if`
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容