سؤال

وأنا جديدة على الثعبان وقررت أن محاولة إعطائها مع TG2 من خلال تطوير متجر صغير. حتى الآن لقد تم تحبه، ولكن أنا على التخمين بأن بلدي يطوفون الترميز لا تزال تعلق جدا لمثل جافا وعلى سبيل المثال، طريقة add to cart في بلدي 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']

وهذا هو بالتأكيد ليست أفضل طريقة لتحقيق ذلك، ولكن حتى الآن يعمل المتوقع كما. في جافا أود أن يكون فقط لتحديث الكائن عنصر، ولكن هنا لا بد لي من إزالته من القائمة ثم تحديثها، ثم اضاف مرة أخرى، وهذا هو الصحيح؟

هل كانت مفيدة؟

المحلول

ومنذ كنت تقوم بتعديل الكائن item، وأنا لا أرى أي سبب لماذا عملتم لإزالة، ثم إلحاق هذا البند إلى القائمة. لماذا تعتقد أن لديك ل؟

وكما لجعل هذا أكثر pythonic، قد تفكر في شيء من هذا القبيل:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top