less than or equal to 0 - is not showing posts which have 0 votes

Viewed 67

I am building a simple question and answer site, and I am trying to access the answers which votes are less than or equal to 0.

I have three answers which have no votes, but it is not showing in the queryset

I should show me three posts which have zero votes, but it is showing 0.

models.py

class Answer(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    body = models.CharField(max_length=3000)
    likes = models.ManyToManyField(User, related_name='likes', blank=True)

views.py

def answers(request):
    answers = Answer.objects.filter(likes__lte=0).count()

    context = {'answers':answers}
    return render(request, 'answers.html', context}

When I remove .count(), then it shows <QuerySet []>.

I have tried many times but it is still showing 0 posts which have 0 votes.

And when I set it to lte=1, then it shows posts which have 1 like but it doesn't show less than 0.

Edit 1 :-

When i tried according to below answer like :-

answers = Answer.objects.filter(likes__level__lte=0).count()

Then it is keep showing

Related Field got invalid lookup: level

1 Answers

try like this bro

def answers(request):
   answers = Answer.objects.filter(likes__level__lte=0).count()

   context = {'answers':answers}
   return render(request, 'answers.html',context} 

Likewise, lt for less than and gt for greater than.

for further reference https://docs.djangoproject.com/en/3.2/ref/models/querysets/

EDIT

level will be the field name in your model User.

Related