Dynamically filter ListView CBV in Django 1.7

前端 未结 1 472
滥情空心
滥情空心 2020-12-31 10:39

I\'ve read the official documentation on dynamically filtering ListView, but am still confused about how to actually use it.

I currently have a simple model, let\'s

相关标签:
1条回答
  • 2020-12-31 10:50

    First of all you need to change your urls.py so that it'll pass the experience as a parameter. Something like this:

    urlpatterns = patterns('',
        url(r'^(?P<exp>[ASG])$', ScholarshipDirectoryView.as_view(), name='scholarship_directory'),
    )
    

    (the above will return 404 if /A or /S or /G is not passed)

    Now, in kwargs attribute of the CBV we will have a kwarg named exp which can be used by the get_queryset method to filter by experience level.

    class ScholarshipDirectoryView(ListView):
        model = Scholarship
        template_name = 'scholarship-directory.html'
    
        def get_queryset(self):
            qs = super(ScholarshipDirectoryView, self).get_queryset()
            return qs.filter(experience_level__exact=self.kwargs['exp'])
    
    0 讨论(0)
提交回复
热议问题