[Answered ]-How to use Group by clause without model's id in Django ORM?

1👍

Use .order_by(…) [Django-doc]:

from django.db.models import Count

result = Model1.objects.values('category').annotate(
    Count('sns_type')
).order_by('category')

That being said, repeating the same category as a CharField is usually not a good idea. Usually one works with a ForeignKey to a Category model as part of database normalization [wiki]:

class Category(models.Model):
    name = models.CharField(max_length=32)


class Model1(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=32)

Then you query with:

from django.db.models import Count

Category.objects.annotate(model1_count=Count('model1'))

Leave a comment