Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass url argument to ListView queryset

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?


1 Answers

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.

like image 118
Aamir Rind Avatar answered Sep 14 '25 18:09

Aamir Rind