3

I am trying to get the count of infringements in the market place for the logged in user. The logged user is part of a group. The problem I am having is its still counting values for marketplace items that doesn't belong to the group. It adds 0 in the queryset breaking my charts,

u = request.user.groups.all()[0].id  
mar_count =  Marketplace.objects.annotate(infringement_count=Count('infringement', filter=Q(groups=u)))

The result 'Ebay','Amazon','Facebook','Wallmart', '0','0','0','0','1','1','1','1',

I should be getting 'Ebay','Amazon','Facebook','Wallmart', '1','1','1','1',

How do I exclude counting the marketplace when its no part of the logged in users group? I am new. Thanks

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Farid
  • 130
  • 9

1 Answers1

2

You can filter out the Marketplaces, 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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thank you so much, its fixed it. I would appreciated it if you help me solve my other questions. – Farid Nov 13 '22 at 21:28
  • @william van onsem I was wondering if you can help me with my other question I posted. Would really appreciate it! – Farid Nov 17 '22 at 20:17