Question

I want to save an array of objects passed from javascript through ajax to me database. This is my view code:

data2 = json.loads(request.raw_get_data)
    for i in data2:
        print(key)
        obj = ShoppingCart(quantity = i.quantity , user_id = 3, datetime = datetime.now(), product_id = i.pk)
        obj.save()

    return render_to_response("HTML.html",RequestContext(request))

After the first line, i get this in my dictionary: [{'model': 'Phase_2.product', 'fields': {'name': 'Bata', 'category': 2, 'quantity': 1, 'subcategory': 1, 'count': 2, 'price': 50}, 'imageSource': None, 'pk': 1}]

(Only one object in the array right now)

I want to be able access individual fields like quantity, id, etc in order to save the data to my database. When i debug this code, it gives a name error on 'i'. I also tried accessing the fields like this: data2[0].quantity but it gives this error: {AttributeError}dict object has no attribute quantity.

Edited code:

for i in data2:
        name = i["fields"]["name"]
        obj = ShoppingCart(quantity = i["fields"]["quantity"] , user_id = 3, datetime = datetime.now(), product_id = i["fields"]["pk"])
        obj.save()
Was it helpful?

Solution

It might help you to visualise the returned dict with proper formatting:

[
    {
     'model': 'Phase_2.product',
     'fields': {
                'name': 'Bata',
                'category': 2, 
                'quantity': 1, 
                'subcategory': 1, 
                'count': 2, 
                'price': 50
               },
     'imageSource': None,
     'pk': 1
    }
]

The most likely reason for your error is that you are trying to access values of of the inner 'fields' dictionary as if they belong to the outer i dictionary.

i.e.

# Incorrect
i["quantity"]
# Gives KeyError

# Correct
i["fields"]["quantity"]

Edit

You have the same problem in your update:

# Incorrect
i["fields"]["pk"]

# Correct
i["pk"]

The "pk" field is in the outer dictionary, not the inner "fields" dictionary.

OTHER TIPS

You may try:

i['fields']['quantity']

The json.loads() returns you a dictionary, which should be accessed by key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top