2016-03-27 8 views
2

「オンラインストア」の章(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}) 
    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 
ビューで

、型エラー辞書の原因であるカートにitem ['update_quantity_form'] = CartAddProductForm(...)を追加しようとしていないでしょうか? TypeError: 'int' object does not support item assignmentのようなもの?その後、

私はカートを模倣するIDLEに辞書を作成する場合は、cart[1]={'quantity':30, 'price':15.00}cart[2] = {'quantity':2, 'price':11.00}は私が明らかに(上記のような)タイプエラーを取得for item in cart: item['update_quantity_form']='form'を行います。

私は本のコードがどのように機能するのか分かりません。私は何か非常にシンプルなものを見逃していますが、それにもかかわらずそれを見逃しています。前もって感謝します。

編集:Iterメソッドを追加するように編集しました。これは私の質問に対する答えかもしれません。

答えて

1

カートはCartオブジェクトとして保存されます。ではありません。dictです。オーバーライドされた__iter__メソッドは、forループの動作が異なります。方法の最後のyield itemには、のうちの1つが格納されています(dict)。だから、IDLEに次のよう多かれ少なかれ等価です:

エラーなしで動作します
>>> 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}} 
+0

ありがとうございました!ええ、私はちょうどそれに追いついていたので、編集。私を混乱させたのは、__iter__メソッドをオーバーライドし、__next__をオーバーライドしないことでした。私が見たほとんどの例は、iterメソッドで 'self'を返し、次のメソッドで作業を行いました。 。 。再びありがとう。 –

関連する問題