我试图显示我的django项目中每个类别的文章数量。但是它显示的是类别id而不是category_name。我想显示category_name和相应的文章数量。
blog/views.py
def searchView(request):
statistics = Post.objects.values('cid').annotate(num_articles = Count('cid')).order_by()
return render(request, 'blog/search.html', {'statistics': statistics})
blog/search.html-〉这里stat.cid显示了类别id,但是我想在这里显示category_name。
{% extends 'users/base.html' %}
{% block content %}
<div class="container">
<br>
<div class="row text-center">
<div class="col-md-3"> </div>
<div class="col-md-6">
<h4 class="p-2 mb-2 bg-secondary text-white">POPULAR CATEGORIES!!</h4>
<table id="myTable" class="table table-bordered table-hover table-striped shadow-sm bg-white rounded">
<thead>
<tr>
<th>Category</th>
<th>Articles Available</th>
</tr>
</thead>
<tbody>
{% for stat in statistics %}
<tr>
<td>
{{ stat.cid }}
</td>
<td>
{{ stat.num_articles }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock content %}
blog/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class Category(models.Model):
cid = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name
class Post(models.Model):
aid = models.AutoField(primary_key=True)
image = models.ImageField(default='blog-default.png', upload_to='images/')
title = models.CharField(max_length=200)
content = RichTextField()
created = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='specialization')
approved = models.BooleanField('Approved', default=False)
like = models.ManyToManyField(get_user_model(), related_name='likes', blank=True)
def __str__(self):
return self.title
2条答案
按热度按时间kupeojn61#
Post.objects.values('cid')
只会给予Category
的pk
。要访问Category
的category_name
,还应将其包含在values()中:现在
category_name
已经可用,请在模板中访问它,如下所示:虽然这是特定于您的情况,一个更好的答案在这里:
https://stackoverflow.com/a/27181936/10951070
am46iovg2#
我将从相反的方向进行,这意味着我将从
Category
访问此数据,而不是从Post
访问,出于某种原因,您将其称为statistics
。首先,我建议您使用
ListView
,然后我将按照以下步骤进行操作:如果你在
cid
属性中的Post
模型中添加一个related_name
,并将其命名为posts
,那么你可以在模板中写入category.posts.count
,这样更容易阅读,这只是个人喜好,绝对不是规则。