Django: get_object extension for class based views

As a non-specialist Python programmer, I'm looking for feedback on how I extended the get_object method of the Django SingleObjectMixin class.

For most of my detailed views, searching with pk or slugfield is fine, but in some cases I need to get an object based on other (unique) fields, for example. "Username". I subclassed Django DetailView and modified the get_object method as follows:

# extend the method of getting single objects, depending on model def get_object(self, queryset=None): if self.model != mySpecialModel: # Call the superclass and do business as usual obj = super(ObjectDetail, self).get_object() return obj else: # add specific field lookups for single objects, ie mySpecialModel if queryset is None: queryset = self.get_queryset() username = self.kwargs.get('username', None) if username is not None: queryset = queryset.filter(user__username=username) # If no username defined, it an error. else: raise AttributeError(u"This generic detail view %s must be called with " u"an username for the researcher." % self.__class__.__name__) try: obj = queryset.get() except ObjectDoesNotExist: raise Http404(_(u"No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj 

Is this a good practice? I try to have one subclass of Detailview that adjusts to different needs when I need to retrieve different objects, but also supports default behavior for ordinary cases. Or is it better to have more subclasses for special occasions?

Thank you for your advice!

+7
source share
2 answers

You can set the slug_field variable in the DetailView class in the model field that should be used for the search! In url templates, you should always call it slug , but you can map it to any model field that you want.

In addition, you can also override the DetailView get_slug_field method, which returns only self.slug_field by default!

+9
source

Can you use inheritance?

 class FooDetailView(DetailView): doBasicConfiguration class BarDetailView(FooDetailView): def get_object(self, queryset=None): doEverythingElse 
0
source

All Articles