Django 将表单添加到Dict中,导致循环混淆
我正在阅读“在线商店”第(6)章中的“Django By Example”,我对视图中的一段简单代码感到有点困惑:Django 将表单添加到Dict中,导致循环混淆,django,python-2.7,Django,Python 2.7,我正在阅读“在线商店”第(6)章中的“Django By Example”,我对视图中的一段简单代码感到有点困惑: def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],'update': True}) re
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})
它显然为购物车中的每个产品添加了一个表单,因此可以更新数量(购物车中的每个产品)。Cart只是一个保存在会话中的dict,这就引出了我的问题
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 loop,尝试将项['update\u quantity\u form']=CartAddProductForm(…)
添加到作为dict的购物车中不会导致类型错误吗?类似于TypeError的内容:“int”对象不支持项分配
如果我在空闲状态下做一个dict来模拟一个购物车,cart[1]={'quantity':30,'price':15.00}
和cart[2]={'quantity':2,'price':11.00}
然后对购物车中的物品执行操作:物品['update\u quantity\u form']='form'
我显然得到了一个类型错误(如上所述)
所以,我不明白他书中的代码是如何工作的。我意识到我错过了一些非常简单的东西,但还是错过了。提前谢谢
编辑:编辑以添加Iter方法,我认为这可能是我问题的答案。购物车存储为
cart
对象,而不是简单的dict
。被重写的\uuu iter\uu
方法会导致for
循环的行为不同。注意方法末尾的yield项
,该项将生成存储的dict
的.values()
。因此,在怠速状态下,它大致相当于以下各项:
>>> cart = {}
>>> cart[1] = {'quantity':30, 'price':15.00}
>>> cart[2] = {'quantity':2, 'price':11.00}
>>> for item in cart.values():
... item['update_quantity_form'] = 'form'
...
>>> cart
它将在没有错误和打印的情况下工作
{1: {'price': 15.0, 'update_quantity_form': 'form', 'quantity': 30},
2: {'price': 11.0, 'update_quantity_form': 'form', 'quantity': 2}}
非常感谢。是的,我刚刚理解了,所以编辑。让我困惑的是重写iter方法,而不是重写next方法。我看到的大多数例子,在iter方法中返回了
self
,并在下一个方法中完成了工作。再次感谢你。