- Django Design Patterns and Best Practices
- Arun Ravindran
- 203字
- 2021-06-25 21:32:10
Chaining multiple QuerySets
So far, we have been combining QuerySets of the same type belonging to the same base class. However, we might need to combine QuerySets from different models and perform operations on them.
For example, a user's activity timeline contains all their posts and comments in reverse chronological order. The previous methods of combining QuerySets won't work. A na?ve solution would be to convert them to lists, concatenate, and sort them, as follows:
>>>recent = list(posts)+list(comments) >>>sorted(recent, key=lambda e: e.modified, reverse=True)[:3] [<Post: user: Post1>, <Comment: user: Comment1>, <Post: user: Post0>]
Unfortunately, this operation has evaluated both the lazy QuerySet objects. The combined memory usage of the two lists can be overwhelming. Besides, it can be quite slow to convert large QuerySets into lists.
A much better solution uses iterators to reduce the memory consumption. Use the itertools.chain method to combine multiple QuerySets as follows:
>>> from itertools import chain >>> recent = chain(posts, comments) >>> sorted(recent, key=lambda e: e.modified, reverse=True)[:3]
Once you evaluate a QuerySet, the cost of hitting the database can be quite high.
So, it is important to delay it as long as possible by performing only operations that will return QuerySets unevaluated.
Keep QuerySets unevaluated as long as possible.
- Vue.js設計與實現
- 數據庫程序員面試筆試真題與解析
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- AIRAndroid應用開發實戰
- R語言數據可視化實戰
- Internet of Things with the Arduino Yún
- Java Web應用開發技術與案例教程(第2版)
- Kotlin從基礎到實戰
- 批調度與網絡問題的組合算法
- Hands-On Nuxt.js Web Development
- 超簡單:Photoshop+JavaScript+Python智能修圖與圖像自動化處理
- The Statistics and Calculus with Python Workshop
- Web開發的平民英雄:PHP+MySQL
- 嵌入式C編程實戰
- C++17 By Example