6

self.get_object()有没有一种既定的方法可以在稍后在 get/post 中调用时验证调度中的对象而不进行额外的数据库调用?

这是我到目前为止的内容(针对这个问题略有改动):

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)
4

1 回答 1

7

您可以缓存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
于 2013-02-12T16:21:56.340 回答