在其类别下显示 Todo [Django]

Display Todo under its category [Django]

我不确定如何提出这个问题,但我会试一试。

我正在编写一个待办事项应用程序,并希望在模板中的相应类别下显示每个待办事项。例如

Display each category
{% for category in categories %}
    <h2>{{ category.name }}</h2>

    Now show each todo that falls under the above category
    {% for todo in todos %}
        <p>{{ todo.description }}</p>
    {% endfor %}
{% endfor %}

如何创建一个查询集来提供这种类型的结构?还是有不同的方法可以实现?

如果有什么不清楚或需要更多信息,请告诉我,我会将其添加到 post

感谢任何帮助,谢谢。

型号

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

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.name


class Todo(models.Model):
    # Priority choices
    PRIORITY_CHOICES = (
        ("bg-danger", "High"),
        ("bg-info", "Normal"),
        ("bg-warning", "Low"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    description = models.CharField(max_length=255)
    priority = models.CharField(max_length=200, choices=PRIORITY_CHOICES, null=True)
    completed = models.BooleanField(default=False)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    category = models.ManyToManyField(Category)

    def __str__(self):
        return self.description

查看

def todo_listview(request):

    template_name = "todos/listview.html"
    context = {
        "todos": get_users_todos(user=request.user),
        "categories": Category.objects.all(),
    }

    return render(request, template_name, context)

您可以预取用户的 Todos,使用:

from django.db.models import <strong>Prefetch</strong>

def todo_listview(request):
    template_name = 'todos/listview.html'
    context = {
        'categories': Category.objects.prefetch_related(
            Prefetch('todo_set'<strong>, queryset=get_users_todos(user=request.user), to_attr='user_todos'</strong>)
        )
    }

    return render(request, template_name, context)

然后渲染:

Display each category
{% for category in categories %}
    <h2>{{ category.name }}</h2>

    {% for todo in <strong>category.user_todos</strong> %}
        <p>{{ todo.description }}</p>
    {% endfor %}
{% endfor %}

由于CategoryTodo之间存在多对多字段,所以相同Todo可能会打印 多次 次:每个类别一次。


Note: The documentation advises to use the AUTH_USER_MODEL setting [Django-doc] over get_user_model() [Django-doc]. This is safer, since if the authentication app is not yet loaded, the settings can still specify the name of the model. Therefore it is better to write:

from django.conf import settings

class Todo(models.Model):
    # …
    user = models.ForeignKey(
        <b>settings.AUTH_USER_MODEL</b>,
        on_delete=models.CASCADE
    )