使用Django的Q从CBV获得搜索结果

时间:2018-04-09 12:25:08

标签: python django django-views

我正在尝试在我的CBV ListView中实现一个简单的搜索功能,下面是我的ListView的样子

class Postlist(SelectRelatedMixin, ListView):
    model = Post
    select_related = ('user', 'group')

我想实现这样的目标(资料来源:Youtube video on how to add search

def post_list(request):
    posts = Post.objects.all()
    query = request.GET.get('q')
    if query:
        posts = Post.objects.filter(
            Q(title__icontains=query)|
            Q(user__username=query)|
            Q(body__icontains=query)

        )
    context = {
        'posts': posts,
    }
    return render(request, 'blog/post_list.html', context)

但我想我无法解释SelectRelatedMixin。我也没关系。 FBV或CBV,只要我可以进行搜索工作

我尝试了下面的代码。我得到NameError:名称'query'未定义

class Postlist(SelectRelatedMixin, ListView):
    model = Post    

    posts = Post.objects.filter(
        Q(title__icontains=query) |
        Q(user__username=query) |
        Q(body__icontains=query)
    ).select_related('user', 'group')

1 个答案:

答案 0 :(得分:4)

在基于功能的视图中,您只需在查询集上调用select_related()即可。

posts = Post.objects.filter(
    Q(title__icontains=query)|
    Q(user__username=query)|
    Q(body__icontains=query)
).select_related('user', 'group')

在基于班级的视图中,您可以覆盖get_queryset

class Postlist(SelectRelatedMixin, ListView):
    model = Post
    select_related = ('user', 'group')

    def get_queryset(self):
        queryset = super(Postlist, self).get_queryset()
        query = self.request.GET.get('q')
        if query:
            queryset = queryset.filter(
                Q(title__icontains=query)|
                Q(user__username=query)|
                Q(body__icontains=query)
            )
        return queryset