在下面的示例代码中,调度方法中的变量声明是否有效? 如果不是CBV有更好的编码标准吗?我的想法是避免在每个http方法中重新声明相同的变量
class MyClsName(View):
template_name = "setup/code_install.html"
def dispatch(self, request, *args, **kwargs):
self.name = request.session['name']
self.obj = MyModel.objects.get(Name=self.name)
return super(MyClsName, self).dispatch(request, *args, **kwargs)
def get(self, request):
# obj = MyModel.objects.get(Name=self.name) --> to avoid
context = {'account': self.obj}
return render(request, self.template_name, context)
def post(self, request):
# obj = MyModel.objects.get(Name=self.name) --> to avoid
context = {'account': self.obj}
return render(request, self.template_name, context)
答案 0 :(得分:2)
这不是无效的,但绝对没有利用基于类的视图的功能。很少需要覆盖dispatch或get / post中的任何一个。相反,您应该为子类选择更合适的视图,并覆盖它提供的特定方法。在这种情况下,由于您要显示单个对象,因此相应的基类是DetailView,要覆盖的方法是public function __destruct()
{
error_log('destructing product');
$this->picture = null;
$this->defaultInsideDimensions = null;
$this->defaultOutsideDimensions = null;
$this->company = null;
$this->snippet = null;
$this->pdfSnippet = null;
$this->superStructureType = null;
if ($this->superStructures instanceof ArrayCollection) {
foreach ($this->superStructures as $superStructure) {
$superStructure->__destruct();
}
}
error_log('product destructed');
}
。
get_object
请注意,根本不需要定义发送,获取或发布。