[Answered ]-Convert raw sql query to django orm

1👍

You can query with:

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

IssueLog.objects.values(
    year=ExtractYear('issue_date'),
    month=ExtractMonth('issue_date')
).annotate(
    total=Count('pk')
).order_by('-year', '-month')

This will make a queryset with dictionaries that look like:

<QuerySet [
    {'year': 2022, 'month': 2, 'total': 14},
    {'year': 2022, 'month': 1, 'total': 25},
    {'year': 2021, 'month': 12, 'total': 13}
]>

I would not do string formatting in the database query, but just do this in the template, etc.

But the model can not be abstract = True [Django-doc]: that means that there is no table, and that it is only used for inheritance purposes to implement logic and reuse it somewhere else.

Leave a comment