将url参数传递给ListView查询集

时间:2013-10-14 13:02:46

标签: django django-urls

models.py

class Lab(Model):
    acronym = CharField(max_length=10)

class Message(Model):
    lab = ForeignKey(Lab)

urls.py

urlpatterns = patterns('',
    url(r'^(?P<lab>\w+)/$', ListView.as_view(
        queryset=Message.objects.filter(lab__acronym='')
    )),
)

我想将lab关键字参数传递给ListView查询集。这意味着如果lab等于TEST,则生成的查询集将为Message.objects.filter(lab__acronym='TEST')

我该怎么做?

2 个答案:

答案 0 :(得分:14)

您需要为此编写自己的视图,然后才覆盖get_queryset方法:

class CustomListView(ListView):
    def get_queryset(self):
        return Message.objects.filter(lab__acronym=self.kwargs['lab'])

并在网址中使用CustomListView

答案 1 :(得分:1)

class CustomListView(ListView):
    model = Message

    def get(self, request, *args, **kwagrs):
        # either
        self.object_list = self.get_queryset()
        self.object_list = self.object_list.filter(lab__acronym=kwargs['lab'])

        # or
        queryset = Lab.objects.filter(acronym=kwargs['lab'])
        if queryset.exists():
            self.object_list = self.object_list.filter(lab__acronym=kwargs['lab'])
        else:
            raise Http404("No lab found for this acronym")
        context = self.get_context_data()
        return self.render_to_response(context)