Home > other >  How to search using queryset on Django
How to search using queryset on Django

Time:04-26

I have Topic model and Post model.

I want to search using queryset. When q has string it work well, however when q = '' (which means All ) it doesn't show all post.

How can I fix this?

All code here

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')

CodePudding user response:

Maybe changing your get_queryset method in your PostListView to:

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')

solves your problem.

CodePudding user response:

You check the truthiness and return Post.objects.none() in case q has truthiness 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()

CodePudding user response:

try this one

        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')
  • Related