pythondjangofilteringexclude-constraint

How to exclude null values in queryset for charts.js


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


Solution

  • 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.