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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Django's aggregation features can do this quite simply.
Now each item in
statuses
has an attributetask__count
which is the number of tasks related to that status.