How to combine two or more querysets in a Django view?

后端 未结 13 2348
猫巷女王i
猫巷女王i 2020-11-21 22:40

I am trying to build the search for a Django site I am building, and in that search, I am searching in 3 different models. And to get pagination on the search result list, I

13条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 23:22

    Related, for mixing querysets from the same model, or for similar fields from a few models, Starting with Django 1.11 a QuerySet.union() method is also available:

    union()

    union(*other_qs, all=False)
    

    New in Django 1.11. Uses SQL’s UNION operator to combine the results of two or more QuerySets. For example:

    >>> qs1.union(qs2, qs3)
    

    The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

    union(), intersection(), and difference() return model instances of the type of the first QuerySet even if the arguments are QuerySets of other models. Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don’t matter as long as the types in the same order).

    In addition, only LIMIT, OFFSET, and ORDER BY (i.e. slicing and order_by()) are allowed on the resulting QuerySet. Further, databases place restrictions on what operations are allowed in the combined queries. For example, most databases don’t allow LIMIT or OFFSET in the combined queries.

提交回复
热议问题