Django: Display a model and a count of how often another model uses it

发布于 2022-09-06 08:11:57 字数 1175 浏览 17 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞎闹 2022-09-13 08:11:57

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文