Django Class Based View: Validate object in dispatch

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-07 14:33:29

问题


Is there a established way that i validate an object in the dispatch without making an extra database call when self.get_object() is called later in get/post?

Here is what i have so far (slightly altered for this question):

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:


You can cache the result of get_object().

Here's a trivial example:

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


来源:https://stackoverflow.com/questions/14836913/django-class-based-view-validate-object-in-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!