如何创建查询以在Django中列出类别

问题描述 投票:1回答:1

我在view.py中找到了这个,想列出所有类别

def home(request):

    category = Category.objects.all()

    context = {

        'category': category,
    }

    return render(request, 'courses/index.html', context)

model.py

class Category(models.Model):
    title = models.CharField(max_length=30, null=True)
    slug = models.SlugField(max_length=30, unique=True)


class Course(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=30, unique=True)

但是我从打印中得到了这个输出:

<QuerySet [<Category: Courses>, <Category: Computers>]>

有人可以帮我吗

django django-queryset
1个回答
1
投票

category不是单个类别。但是类别的集合,您需要对其进行iterate,例如:

def home(request):
    categories = Category.objects.all()
    context = {
        'categories': categories,
    }
    return render(request, 'courses/index.html', context)

在模板中进行迭代,并可以使用以下方式呈现:

{% for category in categories %}
    {{ category }}
{% endfor %}

EDIT:您可以用related Course个对象的数量注释您的查询集:

from django.db.models import Count

def home(request):
    categories = Category.objects.annotate(
        num_courses=Count('course')
    )
    context = {
        'categories': categories,
    }
    return render(request, 'courses/index.html', context)

然后您可以使用:

{% for category in categories %}
    {{ category }}: {{ category.num_courses }}
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.