简体   繁体   English

检查视图中传入的 object 是否存在

[英]Checking in views whether the object passed in context exists or not

I am working on a basic django website.我正在开发一个基本的 django 网站。 I am having a cart view as following:我的购物车视图如下:

def cart(request):
    customer=request.user.customer
    order, created=Order.objects.get_or_create(customer=customer, complete=False)
    items=order.orderitem_set.all()
    context={
        'items':items,
        'order':order,
        'types' : Category.objects.all(),
    }
    return render(request,"cart.html",context)

The items is the products that the customer has in his cart. items 是客户购物车中的产品。 I want to perform a check whether if the cart is empty(that is there are no items) then I can show a message that cart is empty and then can redirect to a certain page.我想检查购物车是否为空(即没有商品),然后我可以显示一条消息,说明购物车为空,然后可以重定向到某个页面。 I am trying to find a way to perform this check and show a message that cart is empty.我试图找到一种方法来执行此检查并显示购物车为空的消息。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks.谢谢。

check exists() --(django doc)检查exists() ——(django 文档)

context={
        'is_empty':order.orderitem_set.exists(),
        'items':items,
        'order':order,
        'types' : Category.objects.all(),
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM