从django数据库获取字段值

时间:2017-02-27 17:20:10

标签: 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 个答案:

答案 0 :(得分:1)

你要回来了

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

并将其分配给calculation。 您的calculation['calculation']Calculation对象没有__getitem__方法,因此您无法像dict那样使用它。

你应该改为

price = calculation['calculation'].purchase_price