Pass url argument to ListView queryset

本秂侑毒 提交于 2019-11-30 06:52:27

You need to write your own view for that and then just override the get_queryset method:

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

and use CustomListView in urls also.

Umar Asghar
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")

        # in both cases
        context = self.get_context_data()
        return self.render_to_response(context)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!