2017-02-27 159 views
0

我有一個靜態方法,我保存用戶(如果存在)和計算。從django數據庫獲取字段值

@staticmethod 
    def save_calculation(user, selection, calculation_data): 
     customer = None 

     if calculation_data['firstname'] or calculation_data['lastname']: 
      customer = Customer() 
      customer.title = calculation_data['title'] 
      customer.firstname = calculation_data['firstname'] 
      customer.lastname = calculation_data['lastname'] 
      customer.save() 


     n_calculation = Calculations() 
     n_calculation.user = user 
     n_calculation.category = selection['category_name'] 
     n_calculation.make = selection['make_name'] 
     n_calculation.model = selection['model_name'] 
     n_calculation.purchase_price = selection['purchase_price'] 
     n_calculation.customer = customer 
     n_calculation.save() 
     return {'statusCode': 200, 'calculation': n_calculation, 'customer': customer} 

和視圖,在這裏我想要得到的結果如下:

def adviced_price(request): 

if request.method == 'POST': 
    connector = Adapter(Connector) 
    selection = Selection(request).to_dict() 
    calculation = connector.calculations(request.user, selection, request.POST) 

    if 'statusCode' in calculation and calculation['statusCode'] == 200: 
     customer = '' 
     if 'customer' in calculation: 
      customer = calculation['customer'] 

     price = calculation['calculation']['purchase_price'] # How to get the price 
     context = {"calculation_data": calculation['calculation'], 'customer': customer, 'price': price} 
     return render(request, 'master/result-calculation.html', context) 
    else: 
     return 
else: 
    return HttpResponse('Not POST') 

我在視圖中獲得的計算如下:

{'statusCode': 200, 'calculation': <Calculations: Calculation for user>, 'customer': None} 

哪有我現在從計算得到purchase_price?我試着用

price = calculation['calculation']['purchase_price'] 

但我得到一個錯誤:TypeError: 'Calculations' object is not subscriptable

有什麼建議?

回答

1

您正在返回

{'statusCode': 200, 'calculation': <Calculations: Calculation for user>, 'customer': None}

並將其分配給calculation。 您的calculation['calculation']Calculation對象,它沒有__getitem__方法,所以你不能像dict那樣使用它。

而應該做

price = calculation['calculation'].purchase_price