class CartManager(models.Manager):
'''
A custom Manager method can return anything you want.
It doesn’t have to return a QuerySet.
'''
def new(self, user=None):
'''使用模型管理器创建一个新对象'''
user_obj = None
if user is not None:
if user.is_authenticated():
user_obj = user
return self.model.objects.create(user=user_obj)
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = self.get_queryset().filter(id=cart_id)
if qs.count() == 1:
# 使用已存在的cart对象,修改其user属性
cart_obj = qs.first()
if request.user.is_authenticated() and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
else:
# 创建新的cart对象,并将其与session绑定
cart_obj = self.new(user=request.user)
request.session['cart_id'] = cart_obj.id
return cart_obj