[Django]-Write an Effective query for django for a FOR Loop?

3👍

You can extract the month and order by that month with an ExtractMonth expression [Django-doc]:

from django.db.models import Count
from django.db.models.functions import ExtractMonth

Insurance.objects.values(month=ExtractMonth('date_purchased_on')).annotate(
    count=Count('pk')
).order_by('month')

This will product a QuerySet of dictionaries that look like:

<QuerySet [
    {'month': 6, 'count': 100 },
    {'month': 7, 'count': 20 }
]>

Months for which there is no Insurance object will not be included in the QuerySet. You thus might have to post-process it and include records with 'count': 0 for these.

Leave a comment