Skip to content
Advertisement

TypeError ‘Purchase’ object has no attribute ‘__getitem__’ [closed]

views.py

def vendor(request,pk): current_shop = get_current_shop(request) instance =get_object_or_404(Vendor.objects.filter(pk=pk,shop=current_shop,is_deleted=False))

vendor = instance.pk

purchases = Purchase.objects.filter(vendor=instance,is_deleted=False,shop=current_shop)
vendor_return = VendorReturn.objects.filter(vendor__pk=pk,shop=current_shop).values('id','return_date','total','date_added')
transaction = Transaction.objects.filter(shop=current_shop,is_deleted=False,vendor=instance).values('transaction_category__name','time','amount','date_added','vendor')
product_schemes = ProductScheme.objects.filter(vendor=instance,is_deleted=False,from_purchase=False).values('date_added','total_amount')
price_drops = VendorProductPriceDrop.objects.filter(vendor=instance).values('date_added','drop_amount')


result_list = sorted(chain(transaction, purchases, product_schemes, price_drops, vendor_return),key=itemgetter('date_added'),reverse=True)

context = {
    "instance" : instance,
    "purchases": purchases,
    "vendor_return": vendor_return,
    'product_schemes': product_schemes,
    "price_drops": price_drops,
    "transaction": transaction,
    'result_list': result_list,
    "title" : "Vendor : " + instance.name,
    "single_page" : True,
}
return render(request,'vendors/vendor.html',context)

Advertisement

Answer

purchases is a normal QuerySet that yields model instances when iterated over. All your other queries are values querysets, these yield dictionaries when iterated over.

itemgetter will only work on objects that support key lookups, like dictionaries, models do not support this. You need to change all your queries to be the same “type” and use itemgetter or attrgetter appropriately.

A quick fix is to turn purchases into a values queryset

purchases = Purchase.objects.filter(vendor=instance,is_deleted=False,shop=current_shop).values()
Advertisement