I have a model which contains a ManyToManyField
:
class UserHasProduct(Model):
user = ForeignKey(User, on_delete=CASCADE)
products = ManyToManyField(Product)
class Product(Model):
is_nfr = BooleanField(default=False)
I want to annotate my queryset with a simple is_nfr
value that returns True if any of the products
have is_nfr
set to True. The best I could come up with is this:
UserHasProduct.objects.filter(user=self.request.user).annotate(
is_nfr=Count("license_code_products", filter=Q(products__is_nfr=True))
)
That works, but instead of a boolean it returns an integer. Not a huge deal, but I am still wondering if it's possible to return a boolean, and if that would help with query performance in any way (i.e. it can stop as soon as it finds the first match, no idea if it works like that).