23

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='')
    )),
)

I want to pass the lab keyword argument to the ListView queryset. That means if lab equals to TEST, the resulting queryset will be Message.objects.filter(lab__acronym='TEST').

How can I do that?

  • Using "naked" default classes is good idea when you need something stupidly simple - return static static html or make redirect to fixed url. Best way to do do what you want is listed in @AamirAdnan answer (also, there are a lot of examples in django tutorial and docs). – Melevir Oct 14 '13 at 20:01

2 Answers2

39

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.

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
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)
Umar Asghar
  • 3,808
  • 1
  • 36
  • 32