- Django Design Patterns and Best Practices
- Arun Ravindran
- 219字
- 2021-06-25 21:32:10
Set operations on QuerySets
True to their name (or rather the latter half of their name), QuerySets support a lot of (mathematical) set operations. For the sake of illustration, consider two QuerySets that contain the user objects:
>>> q1 = User.objects.filter(username__in=["a", "b", "c"]) [<User: a>, <User: b>, <User: c>] >>> q2 = User.objects.filter(username__in=["c", "d"]) [<User: c>, <User: d>]
Some set operations that you can perform on them are as follows:
- Union: This combines and removes duplicates. Use q1 | q2 to get [<User: a>, <User: b>, <User: c>, <User: d>].
- Intersection: This finds common items. Use q1 and q2 to get [<User: c>].
- Difference: This removes elements in the second set from the first. There is no logical operator for this. Instead use q1.exclude(pk__in=q2) to get [<User: a>, <User: b>].
The same operations can be done on QuerySets using the Q objects:
from django.db.models import Q # Union >>> User.objects.filter(Q(username__in=["a", "b", "c"]) | Q(username__in=["c", "d"])) [<User: a>, <User: b>, <User: c>, <User: d>] # Intersection >>> User.objects.filter(Q(username__in=["a", "b", "c"]) & Q(username__in=["c", "d"])) [<User: c>] # Difference >>> User.objects.filter(Q(username__in=["a", "b", "c"]) & ~Q(username__in=["c", "d"])) [<User: a>, <User: b>]
The difference is implemented using & (and) and ~ (negation). The Q objects are very powerful and can be used to build very complex queries.
However, the Set analogy is not perfect. QuerySets, unlike mathematical sets, are ordered. So, they are closer to Python's list data structure in that respect.
推薦閱讀
- 數據庫程序員面試筆試真題與解析
- Android開發精要
- Mastering QGIS
- Hands-On C++ Game Animation Programming
- GeoServer Beginner's Guide(Second Edition)
- 深入淺出PostgreSQL
- 區塊鏈底層設計Java實戰
- Android項目實戰:手機安全衛士開發案例解析
- Natural Language Processing with Java and LingPipe Cookbook
- RESTful Java Web Services(Second Edition)
- C++語言程序設計
- Android應用開發實戰(第2版)
- Visual C++從入門到精通(第2版)
- 深入大型數據集:并行與分布化Python代碼
- Elastix Unified Communications Server Cookbook