Search code examples
pythondjangodjango-class-based-viewsdjango-listview

Django Custom Queryset Using Listview if Parameters Exist in URL


I have a listview for my blog:

#views.py
class BlogListView(ListView):
    model = Blog
    template_name = 'blog/index.html'
    context_object_name = 'blogs'
    ordering = ['-date_posted']
    paginate_by = 5

#urls.py 
path('', BlogListView.as_view(), name='blog-index'),

In my model I have different type of blogs, such as video blog or text blog. my model is like this:

class Blog(models.Model):
    TYPE = (
        ('Video', 'Video'),
        ('Text', 'Text'),
    )
    type = models.CharField(max_length=10, choices=TYPE, default='Text')

Now I want to use request.GET.get('type') to query different types. For example if I go to the url, 127.0.0.1:8000/?type=video I want only blog that are the type video to show. Is it possible to do this with only this listview, or do I have to create others. I need help with making of this feature.


Solution

  • Yes, you can implement this in the ListView by overriding the .get_queryset(…) method [Django-doc]:

    class BlogListView(ListView):
        model = Blog
        template_name = 'blog/index.html'
        context_object_name = 'blogs'
        ordering = ['-date_posted']
        paginate_by = 5
    
        def get_queryset(self):
            type = self.request.GET.get('type')
            qs = super().get_queryset()
            if type is not None:
                return qs.filter(type__iexact=type)
            return qs