按网址段过滤内容

时间:2013-09-16 21:59:57

标签: django python-3.x django-templates django-views

我有一个电影和电视节目的数据库。我想像这样过滤这些: / productions / = index(all),/ productions / films / = only films,and productions / series / = only tv shows

## urls.py
from django.conf.urls import patterns, url

from productions import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^films/$', views.IndexView.as_view(), name='films'),
    url(r'^series/$', views.IndexView.as_view(), name='series'),
)

## views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic

from productions.models import Production, Director

class IndexView(generic.ListView):
    template_name = 'productions/index.html'
    context_object_name = 'productions_list'

    def get_queryset(self):
        return Production.objects.order_by('-release')

这样的事情最好的做法是什么?在views.py中为每个方法创建一个新方法,或者我可以重用main方法,并通过某种方式解析URL段来调用if(productions.is_movie)之类的东西吗?

1 个答案:

答案 0 :(得分:1)

我会从url中捕获字符串,如下所示:

urlpatterns = patterns('',
    url(r'^(?<query>(films|series|))/$', views.IndexView.as_view(), name='films_series'),
)

然后,在get_queryset()方法中,我会检查你是否需要归还所有,电影或连续剧:

class IndexView(generic.ListView):
    template_name = 'productions/index.html'
    context_object_name = 'productions_list'

    def get_queryset(self):
        # analyze `self.kwargs` and decide should you filter or not, just for example:
        is_all = self.kwargs['query'] == ''
        is_movie = self.kwargs['query'] == 'films' 
        is_series = self.kwargs['query'] == 'series'

        return Production.objects.order_by('-release')  # TODO: filter movies or series