【发布时间】:2013-03-31 04:59:03
【问题描述】:
我正在使用 django 在我的电子商务网站上设置购物车功能。所有项目都在 MySQL 表中输入为cart_items。
提问前,相关代码:
charm = False
if postdata.get('charm_sku'):
charm_sku = postdata.get('charm_sku','')
ch = get_object_or_404(Charm, sku=charm_sku)
#get products in cart
cart_products = get_cart_items(request)
product_in_cart = False
# check to see if item is already in cart
for cart_item in cart_products:
if cart_item.product.id == p.id:
if charm == True:
if cart_item.charm.id == ch.id:
# update the quantity if found
cart_item.augment_quantity(quantity)
product_in_cart = True
else:
if cart_item.charm.id == "":
# update the quantity if found
cart_item.augment_quantity(quantity)
product_in_cart = True
编辑:
如上所示,我重新编写了代码,导致if cart_item.charm.id 都抛出 attirbuteerror:'NoneType' object has no attribute 'id'。在某种程度上,我认为这改善了这种情况,因为我怀疑第一个看起来“成功”的实际上是第一个 if charm == True 失败,因此从未测试过第一个 if cart_item.charm.id == ch.id。问题仍然存在:为什么这会引发 AttributeError,当 For 循环清楚地声明了 cart_item,而 cart_items 显然有一个魅力列和 id 分配给所述列?
编辑 2: 我不能从嵌套的 if 中引用 cart_item 吗?这是我唯一能想到的,但同时我觉得我应该能够,所以也许这是错的?
【问题讨论】:
-
而不是
if x ==True: elif x == False:,最好使用成语if x: else:。如果您必须确定它们是否完全等于True或False,则应使用if x is True: elif x is False:这是因为(例如)0 == False为真,而0 is False为假。 -
不,我没有理由,只是原型代码中的一个愚蠢的语义错误。将修复生产。
标签: python mysql django attributeerror nonetype