基于Django类的视图:在调度中验证对象

时间:2013-02-12 16:18:43

标签: python django django-class-based-views

在get / post中稍后调用self.get_object()时,是否存在我在调度中验证对象而不进行额外数据库调用的既定方法?

这是我到目前为止所做的(对于这个问题略有改动):

class CourseUpdateView(UpdateView):
    def dispatch(self, request, *args, **kwargs):

        self.request = request
        self.kwargs = kwargs
        self.object = self.get_object()

        if self.object.is_online:
            messages.warning(request, "Sorry this one can't be updated")
            return redirect("course:detail", pk=self.kwargs['pk'])

        # this is going to call self.get_object again isn't it?
        return UpdateView.dispatch(self, request, *args, **kwargs)

1 个答案:

答案 0 :(得分:3)

您可以缓存get_object()的结果。

这是一个简单的例子:

class CourseUpdateView(UpdateView):
    # [...] your dispatch method

    def get_object(self):
        # it doesn't matter how many times get_object is called per request
        # it should not do more than one request
        if not hasattr(self, '_object'):
            self._object = super(CourseUpdateView, self).get_object()
        return self._object