作为一个非专业的 Python 程序员,我正在寻找有关我扩展 Django 的 SingleObjectMixin 类的 get_object 方法的反馈。
对于我的大多数详细视图,使用 pk 或 slugfield 进行查找很好 - 但在某些情况下,我需要根据其他(唯一)字段检索对象,例如“用户名”。我继承了 Django 的 DetailView 并修改了 get_object 方法,如下所示:
# 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
这是好习惯吗?我尝试拥有一个 Detailview 的子类,当要检索不同的对象时,它会根据不同的需求进行调整 - 但它也保持常见情况的默认行为。还是为特殊情况有更多的子类更好?
谢谢你的建议!