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

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

    This can be achieved by two ways either.

    1st way to do this

    Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator.

    For an instance

    pagelist1 = Page.objects.filter(
        Q(title__icontains=cleaned_search_term) | 
        Q(body__icontains=cleaned_search_term))
    pagelist2 = Page.objects.filter(
        Q(title__icontains=cleaned_search_term) | 
        Q(body__icontains=cleaned_search_term))
    combined_list = pagelist1 | pagelist2 # this would take union of two querysets
    

    2nd way to do this

    One other way to achieve combine operation between two queryset is to use itertools chain function.

    from itertools import chain
    combined_results = list(chain(pagelist1, pagelist2))
    
    0 讨论(0)
提交回复
热议问题