我是Django的新手!我试图让未经身份验证的用户将产品添加到购物车。当他们登录&刷新购物车与用户相关联。但问题出在经过身份验证的用户身上。当经过身份验证的用户注销并重新登录时,会为他创建一个新购物车。这是我的功能,它会检查我是否需要制作新购物车或获取现有购物车。
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:
new_obj = False
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_obj = Cart.objects.create(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
答案 0 :(得分:0)
您应该将用户添加到过滤器,以确保用户获取购物车,因为您将用户链接到购物车。
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
filter_kwargs = {'id': card_id}
if request.user.is_authenticated():
filter_kwargs.update({'user': request.user})
qs = self.get_queryset().filter(**filter_kwargs)
if qs.count() == 1:
new_obj = False
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_obj = Cart.objects.create(user=request.user)
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
你也可以在模型上查看一个django辅助方法,它可能会为你做这样的事情;
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
filter_kwargs = {'id': card_id}
if request.user.is_authenticated():
filter_kwargs.update({'user': request.user})
cart_obj, created = Cart.objects.get_or_create(**filter_kwargs)
if request.user.is_authenticated() and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
request.session['cart_id'] = cart_obj.id
return cart_obj, created
查看此处的文档; https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create