Sywesk
Sywesk

Reputation: 21

Django ORM order_by

I have two models , Task and TaskComment :

class Task(models.Model):
    title = models.CharField(max_length = 200)
    creationDate = models.DateTimeField('date created')
    lastUpdateDate = models.DateTimeField('date updated')
    description = models.CharField(max_length = 5000)

class TaskComment(models.Model):
    task = models.ForeignKey(Task, related_name='comments')
    message = models.CharField(max_length = 5000)
    creationDate = models.DateTimeField('date created')

Imagine a page where all tasks are listed. And thing i want to do is to order tasks by the number of comments linked to this task. I've tried several this like : Task.objects.all().order_by("comments__count") But it doesn't worked.

Can you help me ?

Upvotes: 1

Views: 862

Answers (1)

Denis Kabalkin
Denis Kabalkin

Reputation: 508

You need Annotation

from django.db.models import Count

Task.objects.all().annotate(num_comments=Count('taskcomment')).order_by('-num_comments')

Upvotes: 2

Related Questions