如何在Django中使用queryset进行搜索



我有Topic模型和Post模型。

我想使用queryset进行搜索。当q有字符串时,它工作得很好,但是当q = "(这意味着所有)时,它不显示所有的post。

我该如何解决这个问题?

此处所有代码

models.py

class Topic(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})

views.py

class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context["topics"] = Topic.objects.all() 
return context
def get_queryset(self):
if self.request.GET.get('q') != None:
q = self.request.GET.get('q')
else:
q = ''
# q = self.request.GET.get('q') if self.request.GET.get('q') != None else ''

return Post.objects.filter(topic__name__icontains=q).order_by('-date_posted')

可能将PostListView中的get_queryset方法更改为:

def get_queryset(self):
q_param = self.request.GET.get('q')
if q_param:
return Post.objects.filter(topic__name__icontains=q_param).order_by('-date_posted')
# if q is empty this will return all objects
return Post.objects.all().order_by('-date_posted')

解决你的问题。

检查q是否为真,返回Post.objects.none()False:

def get_queryset(self):
q = self.request.GET.get('q')
if q:
return Post.objects.filter(topic__name__icontains=q).order_by('-date_posted')
else:
return Post.objects.none()

试试这个

q = request.GET.get('search')
if q is not None and q != u"":
q = request.GET.get('search')
Post.objects.filter(topic__name__icontains=q).order_by('date_posted')
else: 
Post.objects.all().order_by('date_posted')

相关内容

  • 没有找到相关文章

最新更新