Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: extend get_object for class-based views
    text
    copied!<p>Being a non-expert Python programmer, I'm looking for feedback on the way I extended the get_object method of Django's SingleObjectMixin class.</p> <p>For most of my Detail views, the lookup with a pk or slugfield is fine - but in some cases, I need to retrieve the object based on other (unique) fields, e.g. "username". I subclassed Django's DetailView and modified the get_object method as follows:</p> <pre><code># 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, i.e. 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's 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 </code></pre> <p>Is this good practise? I try to have one Subclass of Detailview, which adjusts to differing needs when different objects are to be retrieved - but which also maintains the default behavior for the common cases. Or is it better to have more subclasses for the special cases?</p> <p>Thanks for your advice!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload