2👍
✅
You can filter out the Marketplace
s, so not in the .annotate(..)
clause [Django-doc]:
u = request.user.groups.all()[0].id
mar_count = Marketplace.objects.filter(groups=u).annotate(
infringement_count=Count('infringement')
)
The count will always be one (or zero if ingrigment
is None
).
One of the problems with your code snippet is that it will always only work with the first group of that user, and that can be any of the groups the user is a member of, so it is not very consistent. If you want to count all groups the user
is a member of, you can use:
mar_count = Marketplace.objects.filter(groups__user=request.user).annotate(
infringement_count=Count('infringement')
)
Here the count will always be the number of "matching" groups, or 0
if the infrigment
is NULL
.
Source:stackexchange.com