[英]How can I set an attribute to use in both POST and GET methods in django class-based views?
So I'm building a class-based view that uses data from a table on my db, both on POST and GET methods.所以我正在构建一个基于类的视图,它使用我的数据库中的表中的数据,包括 POST 和 GET 方法。 I've been trying to set an attribute with the table to mitigate the time that it would take to pull the table again for the sake of performance.
我一直在尝试为表设置一个属性,以减少为了性能而再次拉表所需的时间。
Because of how functions/methods work I can't set an attribute like this:由于函数/方法的工作方式,我无法设置这样的属性:
class MyClass (View):
@md(login_required(login_url='login',redirect_field_name=None))
def get(self, request):
con = create_engine('mysql+mysqlconnector://user:password@localhost:8000/schema')
#function to get a dict with db tables
tabs = get_tables(con)
#Trying to make the attribute
self.table = tabs['table_That_I_need']
context{'data':tabs}
return render(request, 'markowitz/markowitz.html',context)
@md(login_required(login_url='login',redirect_field_name=None))
def post(self, request):
#this gives me an error since the attribute was not set
table = self.table
form = MarkowitzForm(request.POST,table)
if form.is_valid():
pass
return render(request, 'markowitz/results.html')
I've been trying to use setattr but it doesn't seem to be working我一直在尝试使用setattr但它似乎不起作用
With self.table = ...
you are essentially setting the attribute on the current instance.使用
self.table = ...
您实际上是在当前实例上设置属性。 And Django creates new instances for each request. Django 为每个请求创建新实例。 Which means, the
table
attribute of one instance isn't shared with another instance.这意味着,一个实例的
table
属性不与另一个实例共享。
What you want to do is to set the attribute on the MyClass
itself:您要做的是在
MyClass
本身上设置属性:
def get(...):
...
if not hasattr(self.__class__, 'table'):
# set table attr if not already present
setattr(self.__class__, 'table', tabs['table_That_I_need'])
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.