官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 平邑县| 麻城市| 江西省| 金沙县| 定边县| 温州市| 梓潼县| 甘孜| 三河市| 阿城市| 阳山县| 宁乡县| 皋兰县| 沙湾县| 和林格尔县| 长岛县| 达州市| 萨迦县| 茂名市| 衡南县| 仙游县| 梨树县| 顺义区| 乌鲁木齐县| 永德县| 广宁县| 玉田县| 社旗县| 北京市| 合阳县| 公主岭市| 蒙自县| 张北县| 巴林左旗| 陕西省| 临江市| 庐江县| 密云县| 通榆县| 凤庆县| 华阴市|