views:

50

answers:

1

I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the add to cart method in my CartController.

def add(self, **kw):
    pid=kw['pid']

    product = model.Product.by_id(pid)

    cart = self.get_cart()

    # check if that product is already on the cart
    isInCart = False
    for item in cart.items:
        if item.product == product:
            # if it is, increment quantity
            cart.items.remove(item)
            isInCart = True
            item.quantity += 1
            cart.items.append(item)
            break

    if not isInCart:
        item = model.CartItem(cart, product, 1, product.normalPrice)
        cart.items.append(item)

    DBSession.add(item)
    DBSession.flush()

    # updating values for fast retrieval showing
    # how many items are in the cart
    self.update_session(cart)

    return u'Item added to cart, %d items in session' % session['cartitems']

This is certainly not the best way to achieve this, but so far it works as expected. In java I would just have to update the Item object, but here I have to remove it from the list then updated, then added again, is this correct?

+3  A: 

Since you are modifying the item object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to?

As for making this more pythonic, you might consider something like this:

items_by_pid = dict([(item.product.pid, item) for item in cart.items])
item = items_by_pid.get(pid, None)
if item is None:
    item = model.CartItem(cart, product, 0, product.normalPrice)
    cart.items.append(item)
item.quantity += 1
retracile
If I don't the item quantity is not updated, like the dbsession doesn't mark as a dirty object so it never saves it's new quantity. My first attempt was without removing it from the list.
Juparave
forget that, bad refresh, it does get updated, thanks. Removing that part from the code.
Juparave
I'm making some guesses as to how your model is setup; such as assuming that '1' was the initial quantity, and that since you retrieve the product by pid, it has a pid member (you may be using 'id' or something, but same idea). You may want to incorporate 'retrieve product item from cart' as a method of the cart itself, and have it return the item with quantity of 0 if it doesn't exist... but you'll have a better feel for that since it's your codebase.
retracile
That's what I've been looking for, a more pythonic way of doing it, thanks for your example. Your guesses are correct, at first I didn't get why did you add the item with '0' quantity, then I saw your last line. Good one.
Juparave
Just to cast item.product.id to a str I changed items_by_pid = dict([(str(item.product.id), item) for item in cart.items])
Juparave