0

So the background detail, Post is a model, and I am basically trying to create a blog, the same blog as the one shown in this video.

Here is the code:

from django.views.generic import ListView, DetailView

from models import Post


class PublishedPostsMixin(object):
    def get_queryset(self):
        queryset = super(PublishedPostsMixin, self).get_queryset()
        return queryset.filter(published=True)


class PostListView(PublishedPostsMixin, ListView):
    # PostListView takes default template name as `post_list.html`,
    # as list was the name it was assigned.
    model = Post
    template_name = 'blog/post_list.html'                            


class PostDetailView(PublishedPostsMixin, DetailView):
    model = Post
    template_name = 'blog/post_detail.html'                          

So, if you can see, PublishedPostsMixin is inheriting from object, so how is it that the super() is working. If you can understand what is going on, could you please explain step by step, I'm a little confused.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • http://stackoverflow.com/questions/607186/how-does-pythons-super-do-the-right-thing Can this be helpful? – oleg May 29 '13 at 15:47
  • The mixin isn't supposed to be used by itself. It will work only when applied to classes which define a `get_queryset` method. – Adrián May 29 '13 at 16:03
  • @AdriánLópez : Thanks, I know that, but how does it work the way it does. – Games Brainiac May 29 '13 at 16:14

1 Answers1

3

The trick is in what super does. It's a dynamic call: it refers to the next class up in the MRO (method resolution order). Because (as Adrián says in the comments) the mixin is only supposed to be used in conjunction with other classes, there will always be something in between PublishedPostsMixin and object in the MRO.

For more details on super, you should read Raymond Hettinger's article Super considered super (note that it's written with Python 3 syntax in mind, but the principles are the same).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895