In the Django queryset docs, the following aggregate operation is performed:
Book.objects.all().aggregate(Avg('price'))
I'm wondering if there's a way to do something similar, but with the or operation. Instead of taking the average on a field with numbers it would take the or of all boolean values for a given attribute
CodePudding user response:
Well, you could think about the logic of your operator. You want to have the OR operator on a column of a queryset. What it means is that you "operator" would return True if any of row have this column to True, and also False other way (False if they are all False).
This can be easly implemented like this:
test_bool = bool(MyModel.objects.filter(my_bool_col=True))
This is because an empty queryset is evaluated to False, either way to True.
This is equivalent to the any() in Python.
To do the same with AND, you could do the opposit: if any is False, then the whole condition is False, so:
test_bool = not bool(MyModel.objects.filter(my_bool_col=False))
CodePudding user response:
I would use the following snippet for that.
bestseller_found = Book.objects.filter(is_bestseller=True).exists()
If you need a bit more advanced logic, you can often use a Django feature for that as well, e.g.
unofficial_book_found = Book.objects.filter(isbn__isnull=True).exists()