superclass SingleObjectMixin

54 views
Skip to first unread message

Dave

unread,
Apr 7, 2012, 11:40:05 AM4/7/12
to Django users
Hi, I need to manipulate my pk when using new class based views. In
order to DRY I think what's needed is to superclass SingleObjectMixin.

I have the following but it's not working. Greatly appreciate help/
suggestions!

In view.py have the below which does not work.

from django.views.generic.detail import SingleObjectMixin
class SingleObjectMixin(SingleObjectMixin):

def get_object(self, *args, **kwargs):
queryset = self.get_queryset()
pk = pid_to_oid(self.kwargs.get('pk'))
queryset = queryset.filter(pk=pk)
obj = queryset.get()
return obj

return super(SingleObjectMixin,self).get_object(self, *args,
**kwargs)

from django.views.generic import ListView, DetailView

but if I do the below it works(but prefer to not have to add this to
each CBV).

class ItemDetailView(DetailView):
model=Item

def get_object(self):
queryset = self.get_queryset()
pk = pid_to_oid(self.kwargs.get('pk'))
queryset = queryset.filter(pk=pk)
obj = queryset.get()
return obj

Thanks in advance for the help.

Dave






Daniel Roseman

unread,
Apr 7, 2012, 11:45:55 AM4/7/12
to django...@googlegroups.com
I'm not quite sure what you're trying to do here, especially in your use of "superclass" rather than the more normal "subclass". In any case, you can't simply subclass something but call your class the same name as the parent class and just expect all references to the superclass to be magically replaced by your class.

The thing I guess you're missing is that SingleObjectMixin is, well, a mixin. So you can just mix it in to your view class:

    class ItemDetailView(MySingleObjectMixin, DetailView): 

and according to Python's rules of inheritance, it will find your get_object method in place of the original one.
--
DR.

Dave

unread,
Apr 7, 2012, 11:56:27 AM4/7/12
to Django users
Thanks Daniel, appreciate the super fast response! I did your
suggestion and it works like a charm. It's better than putting the
method in each class. Was just hoping there is a way I could override
get_object in the singeobjectmixin everywhere vs. adding another mixin
for each CBV. Perhaps i'm just being too lazy....

Thanks again!

Dave
Reply all
Reply to author
Forward
0 new messages