2014-11-20 47 views
0

以下哪项最适合遵循DRY主体 而不必消耗系统内存?内存中的高效DRY练习和Django实例

my_cart_id #this var could hold value or None 

cart = Cart() 
try: 
    cart = Cart.objects.get(id=my_cart_id) 
except Cart.DoesNotExist: 
    pass 
except Exception as e: 
    MyExceptionHandler(e) 

OR

try: 
    cart = Cart.objects.get(id=my_cart_id) 
except Cart.DoesNotExist: 
    cart = Cart() 
except Exception as e: 
    ExceptionHandler(e) 
    cart = Cart() 

OR

cart = None 
try: 
    cart = Cart.objects.get(id=my_cart_id) 
except Cart.DoesNotExist: 
    pass 
except Exception as e: 
    ExceptionHandler(e) 
finally: 
    cart = cart if cart else Cart() 

我更喜欢第一个,但它是最好的?第一种情况通常会创建空购物车实例。如果变量被覆盖,内存是否被回收?

+0

这是真的不清楚你在这里试图做什么。额外的异常处理程序有什么意义?你想抓住什么其他例外? – 2014-11-20 18:31:09

+0

如果你创建一个'Cart',你打算保存吗?如果是这样,那么'get_or_create'就是这种情况:https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create – 2014-11-20 19:13:42

+0

在每种情况下,代码都会添加一些数据,然后保存购物车。如果'cart_id == None',那么使用'get_or_create'仍然是正确的用法,对吗?创建的实例已经以'id = None'开头,对吗? – tomcounsell 2014-11-20 20:14:38

回答

0

感谢您的意见! get_or_create似乎是最好的解决方案。

try: 
    cart, created = Cart.objects.get_or_create(id=my_cart_id) 
except Exception as e: 
    ExceptionHandler(e) 
    cart = Cart() 

#do stuff 
cart.save() 

但是,不知道try甚至在这里是必要的。