Django - 使用getattr()检索模型方法(@property)

时间:2016-03-16 19:15:59

标签: python django django-models getattr

我想这样做:

@property
def total_sale(self):
    return self.sales_price * self.sales_qty

将变量提交为表示我的模型方法之一的字符串:

def total_sales(self):
    return self.retrieve_data(variable="total_sale")

但我的努力不起作用:

LOSS_UNITS[\"GRPY\"]==CDR  
LOSS_USERCURVE_TYPE[\"GRPY\"]==PCT_MULTIPLY  
LOSS_USERCURVE_INDEX_OFFSET[\"GRPY\"]==BY_LOAN_AGE  
LOSS_RATE[\"GRPY\"]==100  
LOSS_NONPERF_ADV_PCT_P[\"GRPY\"]==0  
LOSS_NONPERF_ADV_PCT_I[\"GRPY\"]==0  
SEVERITY_USERCURVE_TYPE[\"GRPY\"]==NONE  

它只是说:

  

' SalesSummaryView'对象没有属性' total_sale'

显然,我误解了用法。有人可以帮助我找到实现这一目标的方法吗?

1 个答案:

答案 0 :(得分:0)

知道了!我在视图上调用了getattr(),而不是模型。我不需要使用self,而是需要提交for invoice in invoice_set: for sale in invoice.salesrecord_set.all(): total += getattr(sale, variable) 对象。

public function postSignin(Request $request)
{
   $this->validate($request, [
    'email' => 'required',
    'password' => 'required'
   ]);

// This line will always log the user **in** if the account is confirmed or not.
if (!Auth::attempt($request->only(['email', 'password']), 
    $request->has('remember')))
{
    return redirect()->back()->with(notify()->flash("Ooops..", "error", [
        'timer' => 5000,
        'text' => 'Could not sign in with those details',
    ]));
}
else if (!Auth::attempt(["email"=>$request->input("email"),"password"=>$request->input('password'),"confirmation"=>1]) 
{
    return redirect()->back()->with(notify()->flash("Ooops..", "error", [
        'timer' => 5000,
        'text' => 'Activate your account',
    ]));
}
else 
{
return redirect()->route('home');
}
}