簡體   English   中英

如何在基於 django 類的視圖中設置要在 POST 和 GET 方法中使用的屬性?

[英]How can I set an attribute to use in both POST and GET methods in django class-based views?

所以我正在構建一個基於類的視圖,它使用我的數據庫中的表中的數據,包括 POST 和 GET 方法。 我一直在嘗試為表設置一個屬性,以減少為了性能而再次拉表所需的時間。

由於函數/方法的工作方式,我無法設置這樣的屬性:

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

我一直在嘗試使用setattr但它似乎不起作用

使用self.table = ...您實際上是在當前實例上設置屬性。 Django 為每個請求創建新實例。 這意味着,一個實例的table屬性不與另一個實例共享。

您要做的是在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM