我在閱讀「在線商店」章節(6)中的「Django By Example」,我對視圖中的一段簡單代碼有點困惑:添加窗體到字典與For循環混淆
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],'update': True})
return render(request, 'cart/detail.html', {'cart': cart})
它明顯地爲購物車中的每個產品添加一個表單,因此數量可以更新(針對購物車中的每個產品)。 。購物車只是一個字典,保存在會議中,這使我想到了我的問題。 。 。
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart= cart
...
def __iter__(self):
"""
Iterate over the items in the cart and get the products from the database.
"""
product_ids = self.cart.keys()
# get the product objects and add them to the cart
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
在視圖for循環,不會嘗試添加到item ['update_quantity_form'] = CartAddProductForm(...)
這是一個字典原因的錯誤類型的車?像TypeError: 'int' object does not support item assignment
?
如果我在做一個空閒的字典模仿車,cart[1]={'quantity':30, 'price':15.00}
和cart[2] = {'quantity':2, 'price':11.00}
然後做for item in cart: item['update_quantity_form']='form'
我顯然得到一個類型錯誤(如上面)。
所以,我不明白他的代碼在書中是如何工作的。我意識到我錯過了一些非常簡單的東西,但仍然錯過了它。提前致謝。
編輯:編輯添加Iter方法,我認爲這可能是我的問題的答案。
謝謝合作!是的,我剛剛接觸到,因此編輯。我感到困惑的是重寫了__iter__方法,而不是覆蓋__next__。我查看的大多數例子都是在iter方法中返回'self',並在下一個方法中完成工作。 。 。再次謝謝你。 –