[Answered ]-Type error with function on queryset

1👍

So, I don’t know anything about your Product object, so here goes my ideas based on the options I see.

1) It could be that result is a string, not a dict, since it seems you are assigning what looks like the first element of an iterable object to it. If this is the case, check what Product.object(…).first() actually returns.

2) It is possible that you wanted to get a list/tuple of dictionaries. In that case, do not choose .first() from Product.objects(..). Then it would make sense to iterate that list of dictionaries with “for i in result:” etc.

3) If you did intend to get the first member of the Product.object(..) tuple, then your for loop actually loops the items of this dictionary. It is very possible that i then becomes a string, which you can only use integer indices for. This will then throw the exception you saw. To fix, remove the for loop.

It appears to me that result is a dictionary, since the assignment to result[‘image’] seems to work fine. In that case, my item 3) applies to your situation. However, I am not sure whether that is the behavior you are looking for?

1👍

Your stacktrace shows that the error is here:

i['price'] = str(i['price']) + ' (Estimate: ' +     
             (symbol(user.settings_currency.symbol)) + 
             ' ' + "{:.2f}".format((exchange(i['price'], i['currency'], 
             user.settings_currency.id,))) + ' )'

Here you are trying i as a dictionary. You can use i[‘somestring’] notation only for dictionaries. But python is telling you that you cannot use it with i because it’s a string! That’s basically what is meant by

Exception Value: string indices must be integers, not str

At any rate, i is not a dictionary says python. But how can that be? Pretty hard to figure out isn’t it. What if your code was simpler? In fact it can be.

    result = Product.objects
        .filter(pk=pk)
        .values('pk', 'name',)
        .annotate(
            currency=F('variation__price__currency'),
            currencycode=F('variation__price__currency__currencycode'),
            symbol=F('variation__price__currency__symbol'),
            price=F('variation__price__price'),
        )
        .order_by('variation__price__created')[0]


    img = Image.objects.filter(variation__product=pk).all().values('image')
    result['image'] = list(set(i["image"] for i in img))

    result['price'] = str(result['price']) + ' (Estimate: ' + (symbol(user.settings_currency.symbol)) + ' ' + "{:.2f}".format((exchange(result['price'], result['currency'], user.settings_currency.id,))) + ' )'

    return Response(result)

Do let me know if the error persists.

👤e4c5

Leave a comment