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

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.

主站蜘蛛池模板: 涟水县| 肇庆市| 吉林省| 宜春市| 达孜县| 方城县| 灵山县| 内丘县| 拜泉县| 岢岚县| 竹山县| 信阳市| 恩施市| 英德市| 通城县| 梅河口市| 抚松县| 二连浩特市| 鹤壁市| 琼中| 青海省| 遵义市| 武城县| 阿拉善左旗| 额尔古纳市| 桃源县| 景宁| 增城市| 乌兰浩特市| 桂平市| 连南| 江陵县| 道真| 开原市| 河池市| 仪陇县| 霍城县| 多伦县| 沛县| 平定县| 上思县|