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

后端 未结 13 2414
猫巷女王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:16

    You can use Union

    qs = qs1.union(qs2, qs3)
    

    But if you want to apply order_by on the foreign models of the combined queryset.. then you need to Select them before hand this way.. otherwise it won't work

    Example

    qs = qs1.union(qs2.select_related("foreignModel"), qs3.select_related("foreignModel"))
    qs.order_by("foreignModel__prop1")
    

    where prop1 is a property in the foreign model

提交回复
热议问题