Home > Mobile >  Exclude if any of statement is true
Exclude if any of statement is true

Time:09-26

I am building a Simple Blog Post web app, And I am trying to exclude items if any of items is true,

But it is checking for all statements, I mean it is checking if all the statements are true which i don't expect.

models.py

class BlogPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    body = models.CharField(max_length=30)

class Rate(models.Model):
    by_user = models.ForeignKey(User, on_delete = models.CASCADE)
    blog_of = models.ForeignKey(BlogPost, on_delete = models.CASCADE)
    rated_1 = models.BooleanField(default=False)
    rated_2 = models.BooleanField(default=False)
    completed = models.BooleanField(default=False)

views.py

def page(request):
    queryset = Rate.objects.filter(completed=False).exclude(rated_1=False, rated_2=False)

    context = {'queryset':queryset}
    return render(request, 'page.html', context)

What's the Output ?

It is showing queryset which is completed=False but not excluding if one of the exclude items is true.

I have tried many times but it is still not working.

Thank You.

CodePudding user response:

According to Django Docs ,

exclude(**kwargs)¶

Returns a new QuerySet containing objects that do not match the given lookup parameters.

The lookup parameters (**kwargs) should be in the format described in Field lookups below. Multiple parameters are joined via AND in the underlying SQL statement, and the whole thing is enclosed in a NOT().

Your code has

exclude(rated_1=False, rated_2=False)

and NOT (TRUE AND FALSE) == NOT (TRUE) = FALSE

NOT (TRUE AND TRUE) == NOT (TRUE) = FALSE

NOT (FALSE AND FALSE) == NOT (FALSE) = TRUE

so the overall statement will evaluate to true only when both rated 1 and rated 2 are TRUE and not if only one of them is.

To exclude OR statements, or for more complex statements, you should use Q Statements

  • Related