Pass url argument to ListView queryset

前端 未结 2 1584
星月不相逢
星月不相逢 2020-12-30 02:27

models.py

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

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

相关标签:
2条回答
  • 2020-12-30 03:07

    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.

    0 讨论(0)
  • 2020-12-30 03:16
    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)
    
    0 讨论(0)
提交回复
热议问题