我目前正在研究该项目的一小部分,以了解有关Django ORM的更多信息并显示单个对象。使用通用视图保持代码干净。(我是Django框架的新手)
本文的目的是显示有多少用户写了一篇文章。例如,我总共有4条文章。我需要显示每个用户写了多少篇文章。
我的控制台输出:
用户 | 文章数 |
---|---|
测试者 | 2 |
测试用户1 | 2 |
测试用户2 | 0 |
我在HTML模板上的输出:
用户 | 文章数 |
---|---|
测试者 | 0 |
测试用户1 | 0 |
测试用户2 | 0 |
我不明白为什么控制台输出正确,但是我的HTML模板没有显示结果。请帮助我理解为什么这样做!!如果有类似的帖子让我知道!我一直到处都在寻找答案,但是我无法在互联网上找到答案。
views.py
from django.views.generic import ListView
from .models import Article
from django.contrib.auth import get_user_model
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
context_object_name='article_list'
queryset=Article.objects.order_by('-date')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
users = get_user_model().objects.all()
context["users"] = users
articles = Article.objects.all()
for user in users:
article_count = articles.filter(author__exact=user).values('author').count()
# works with and without str() function
context['article_count'] = str(article_count)
# My console output is correct
print(str(user) + ': ' + str(articles.filter(author__exact=user).values('author').count()))
return context
models.py
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
class Article(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', args=[str(self.id)])
article_list.html
{% extends 'base.html' %}
{% block title %}Articles{% endblock title %}
{% block content %}
<!-- This is for checking if the articles exist. Nothing to worry here. Output is 4 -->
{% if article_count > 0 %}
<p>{{article_count}} There are articles in this list</p>
{% else %}
<p>There are no articles in this list</p>
{% endif %}
<!-- Main source of the problem!! -->
{% for user in users %}
<p>{{user}} = {{article_count}}</p>
{% endfor %}
<!-- Displays data from database. Nothing to worry here. -->
{% for article in article_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ article.title }}</span> ·
<span class="text-muted">by {{ article.author }} | {{ article.date }}</span>
</div>
<div class="card-body">
{{ article.body }}
</div>
<div class="card-footer text-center text-muted">
<a href="{% url 'article_edit' article.pk %}">Edit</a> |
<a href="{% url 'article_delete' article.pk %}">Delete</a>
</div>
</div>
<br />
{% endfor %}
{% endblock content %}
希望组织得足够了解问题。提前致谢!!!
您只是article_count
在for循环中重写变量,因此,上下文仅分配给最后计算的值。您可以{"user": {"object": user, "article_count": article_count}}
为每个用户创建一个类似的字典,并在对所有用户进行计算之后将该字典分配给上下文,但是,这仍然不是一个明确的方法。
最好的方法是为连接分配一个相关的名称:
class Article(models.Model):
...
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
related_name="articles",
)
然后,在视图中为用户分配上下文:
context["users"] = get_user_model().objects.all()
现在,您可以在模板中显示如下结果:
{% for user in users %}
<p>{{ user }} = {{ user.articles.count }}</p>
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句