【发布时间】:2018-09-18 20:26:42
【问题描述】:
我正在尝试在我的 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: name 'query' is not defined
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')
【问题讨论】:
-
什么是SelectRelatedMixin?功能视图有什么问题,如果它做你想做的事?
-
为什么你不能用功能视图做到这一点?
-
您面临的问题是什么?我们需要更多信息
标签: python django django-views