mercredi 9 décembre 2020

Best way to write an If statement in Python with a queryset that is out of index?

Hey guys I'm trying to do a simple if statement in Python and I get an error any time I try to do a comparison between a queryset that is empty.

What's the best way to write this code so that it doesn't give me an error if there's no fields in the check variable?

If check comes up empty, then I get an error when I run the if(check[0].username == None) statement.

Thanks!

Here's my code:

def upvote(request):
    postID = request.POST.get("postID")
    currentUser = request.POST.get("currentUser")
    username = request.POST.get("username")
    query = NewPost.objects.get(id = postID)
    check = Vote.objects.filter(postID = postID) & Vote.objects.filter(username = currentUser)
    if(check[0].username == None):
        query.rating = query.rating +1
        query.save()
        query2 = User.objects.get(username = username)
        query2.userRanking = query2.userRanking +1
        query2.save()
        new = Vote.objects.create(postID = postID, username = currentUser)
        new.save()
        pyautogui.hotkey('f5')
        return render(request)
    else:
        pyautogui.hotkey('f5')
        return render(request)

Aucun commentaire:

Enregistrer un commentaire