Django:为基于类的视图扩展get_object

时间:2011-07-22 11:13:06

标签: django subclassing django-generic-views

作为一名非专业的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子类,当需要检索不同的对象时,它会根据不同的需求进行调整 - 但这也维护了常见案例的默认行为。或者为特殊情况设置更多子类是否更好?

感谢您的建议!

2 个答案:

答案 0 :(得分:9)

您可以将slug_field类的DetailView变量设置为应该用于查找的模型字段!在网址模式中,它必须始终命名为slug,但您可以将其映射到所需的每个模型字段。

此外,您还可以覆盖DetailView的{​​{1}} - 方法,该方法默认只返回get_slug_field

答案 1 :(得分:0)

你能使用继承吗?

class FooDetailView(DetailView):
    doBasicConfiguration

class BarDetailView(FooDetailView):
    def get_object(self, queryset=None):
        doEverythingElse