Home > Net >  How to count all objects in a queryset related to a specific fields value?
How to count all objects in a queryset related to a specific fields value?

Time:09-25

I have a Model Poller that has a field category. I have a filtered queryset of Poller. Now I would like to count the objects for each category like so:

Poller 1: poller_category - Sport
Poller 2: poller_category - Sport
Poller 3: poller_category - Tech
Poller 4: poller_category - Tech
Poller 5: poller_category - Fashion

should return a dictionary somewhat to counts = {'Sport' : '2', 'Tech' : '2', 'Fashion' : '1'}

# Model

class Poller(models.Model):

    poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
    created_by = models.ForeignKey(Account, on_delete=models.CASCADE)


class Category(models.Model):
    """
    Model to define categories and their color styles
    """
    poller_category = models.CharField(max_length=30)
    category_color = models.CharField(max_length=15, blank=True)
# View / query

    qs = Poller.objects.filter(
        created_by__username=username).order_by(
        '-poller_category')

Not sure but the ordering itself might be obsolet probably.

CodePudding user response:

You can specify for each name Category, the Count of the number of items:

from django.db.models import Count, Q

Category.objects.annotate(
     numpollers=Count('poller', filter=Q(poller__created_by__username=username))
)

Here the Category objects that arise from this queryset will have an extra attribute .numpollers with the number of Poller objects where the created_by__username is set to the username.

  • Related