Django: Display a model and a count of how often another model uses it
I am creating a TODO list that categorizes tasks by their status. IE: Waiting, Today, Tomorrow, Scheduled. My models look something like:
开发者_高级运维class Status(models.Model):
title = models.CharField(max_length=32)
class Task(models.Model):
user = models.ForeignKey(User)
status = models.ForeignKey(Status, default=1)
title = models.CharField(max_length=128)
notes = models.TextField(blank=True)
completed = models.BooleanField()
I want to create a navigation list that displays all of the statuses (which is simple) but also the count of how many tasks are assigned to each (that is where I am stuck).
Waiting(1) Today(3) Tomorrow(1) Scheduled (0)
It needs to be able to produce the status even if the count is 0. It's a navigational list and I want the user to be able to see where they can put a task.
Status.objects.all()
Above will get me my list but I don't know how to get the count of tasks. I figure I have to work in reverse, pull a list of tasks and group them by my Status model but I am at a loss on how to do that.
Django's aggregation features can do this quite simply.
from django.db.models import Count
statuses = Status.objects.all().annotate(Count('task'))
Now each item in statuses
has an attribute task__count
which is the number of tasks related to that status.
精彩评论