无法显示Django中包含文章数量的类别名称

v2g6jxz6  于 2022-12-24  发布在  Go
关注(0)|答案(2)|浏览(113)

我试图显示我的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
kupeojn6

kupeojn61#

Post.objects.values('cid')只会给予Categorypk。要访问Categorycategory_name,还应将其包含在values()中:

# Note the double underscore between cid and category_name
`Post.objects.values('cid', 'cid__category_name')`

现在category_name已经可用,请在模板中访问它,如下所示:

{{ stat.cid__category_name }}

虽然这是特定于您的情况,一个更好的答案在这里:
https://stackoverflow.com/a/27181936/10951070

am46iovg

am46iovg2#

我将从相反的方向进行,这意味着我将从Category访问此数据,而不是从Post访问,出于某种原因,您将其称为statistics
首先,我建议您使用ListView,然后我将按照以下步骤进行操作:

# views

from django.views.generic import ListView

class CategoryListView(ListView):
    model = Category
    template_name = 'blog/search.html'
    context_object_name = "categories"
# template
<table>
    <thead>
    ...
    </thead>
    <tbody>
        {% for category in categories %}
            <tr>
                <td>{{ category.cid }}</td>
                <td>{{ category.post_set.count }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

如果你在cid属性中的Post模型中添加一个related_name,并将其命名为posts,那么你可以在模板中写入category.posts.count,这样更容易阅读,这只是个人喜好,绝对不是规则。

相关问题