23

模型.py

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

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

网址.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')

我怎样才能做到这一点?

4

2 回答 2

36

您需要为此编写自己的视图,然后重写该get_queryset方法:

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

CustomListView在网址中使用。

于 2013-10-14T13:11:21.967 回答
5
class CustomListView(ListView):
    model = Message
    
    def get(self, request, *args, **kwargs):
        # 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")

        # in both cases
        context = self.get_context_data()
        return self.render_to_response(context)
于 2017-05-03T11:43:35.567 回答