1

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.