如何从Django模型中排除值?

2024-04-18 14:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从观察列表中排除一个项目,但它不起作用

我的代码:

def watchlist(request, page_id):
    items = Watchlist.objects.all()
    item = Auction_listings.objects.get(pk=page_id)

    if request.method == "POST":
        if item_id not in items:
            add = Watchlist(auction=item)
            add.save()
        else:
            remove = Watchlist.objects.get(auction=item)
            remove.delete()
            
    return render(request, "auctions/watchlist.html", {
        "items": Watchlist.objects.all()
    })

Tags: addid列表getifobjectsrequestpage
1条回答
网友
1楼 · 发布于 2024-04-18 14:32:43

您可以检查queryset中是否存在该项,然后从那里开始

def watchlist(request, page_id):
    items = Watchlist.objects.all()
    item = Auction_listings.objects.get(pk=page_id)

    if request.method == "POST":
        if not items.filter(auction=item).exists():
            add = Watchlist(auction=item)
            add.save()
        else:
            remove = Watchlist.objects.get(auction=item)
            remove.delete()
            
    return render(request, "auctions/watchlist.html", {
        "items": Watchlist.objects.all()
    })

相关问题 更多 >