12
如何在Django视图中合并两个或多个查询集?
我正在尝试为正在构建的Django网站建立搜索,在该搜索中,我正在3种不同的模型中进行搜索。为了在搜索结果列表上进行分页,我想使用一个通用的object_list视图来显示结果。但是要做到这一点,我必须将3个查询集合并为一个。 我怎样才能做到这一点?我已经试过了: result_list = [] page_list = Page.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term)) article_list = Article.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term)) post_list = Post.objects.filter( Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term)) for x in page_list: result_list.append(x) for x in article_list: result_list.append(x) for x in post_list: result_list.append(x) return object_list( request, queryset=result_list, template_object_name='result', paginate_by=10, extra_context={ 'search_term': …