how can i get the number of products in each countries using my django models

I have a model in Django, I need a way to get the number of products in each country so that I can use that to plot a graph.

NB: I am using the django-countries package in my application

models.py

from django.db import models
from django_countries.fields import CountryField

class Product(models.Model):
    name = models.CharField(max_length=36)    user = models.ForeignKey(User, on_delete=models.CASCADE)
    is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True)
    country = CountryField(blank_label='(select country)')

I want the result to be something like: US: 5 NG: 20 SA: 8

and so on, so I could use it to plot graphs.

Answer

You can work with .annotate(…) [Django-doc]:

from django.db.models import Count

Product.objects.values('country').annotate(
    number=Count('pk')
).order_by('country')

This will make a QuerySet that looks like:

<QuerySet [
    {'country': 'NG', 'number': 20},
    {'country': 'SA', 'number': 8},
    {'country': 'US', 'number': 5}
]>

We can convert this to a dictionary that maps the countries to the corresponding number with:

from django.db.models import Count

qs = Product.objects.values('country').annotate(
    number=Count('pk')
).order_by('country')

result = {
    q['country']: q['number']
    for q in qs
}

Leave a Reply

Your email address will not be published. Required fields are marked *