Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top