2017-02-27 102 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