2

A lot of the time, I see this:

def get_queryset(self):
    queryset = super(SomeView, self).get_queryset()
    return queryset.filter(published=True)

This is typical in a Django class based view. What I'd like to know are, why do we do this, when we can just do this:

queryset = someModel.objects.all().filter(args)

Or if you prefer two lines (or you think I just like one liners, which is not the case here):

all_the_stuff = someModel.objects.all()
the_stuff_we_want = all_the_stuff.filter(...)

Also, how does the logic behind the super() call exactly work, because I simply don't get it. Any link to some good documentation explaining this would be highly appreciated, and why use it, when the second example is so much more understandable.

1 Answer 1

1

If the super class has additional filtering, then the filters will be chained by calling the super's get_queryset method. This might be a rare case, when multiple levels of inheritance are required but it would be more DRY.

class CompanyListView(ListView):
    def get_queryset(self):
        queryset = super(CompanyListView, self).get_queryset()
        return queryset.filter(company=self.company)

class EmployeeListView(CompanyListView):
    def get_queryset(self):
        queryset = super(EmployeeListView, self).get_queryset()
        return queryset.filter(active=True)

class LocationListView(CompanyListView):
    def get_queryset(self):
        queryset = super(LocationListView, self).get_queryset()
        return queryset.filter(published=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.