【问题标题】:Django how to multiply (.count) of one field to another field and show the result in templateDjango如何将一个字段的(.count)乘以另一个字段并在模板中显示结果
【发布时间】:2020-06-13 09:46:14
【问题描述】:

我有一个项目可以给发帖的人加分。

我有两个模型(Post 和 Points)。

我想统计 (Post) 中的每个用户帖子,并将结果乘以 (Points) 中的 create_post_points 字段并在模板中显示结果。

我尝试做的事情(信号、聚合、查询集、模型中的中间类)但我失败了。

谁能帮帮我?

Models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    likes = models.ManyToManyField(User, related_name='likes', blank=True)
    post_date = models.DateTimeField(default=timezone.now)
    post_update = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    favourite = models.ManyToManyField(User, related_name='favourite', blank=True)

class Points (models.Model):
        create_post_points = models.IntegerField()
        create_comment_points = models.IntegerField()

Views.py

def PostListView(request):
posts = Post.objects.all()
context = {
    'title': 'Home Page',
    'posts': posts,
}
return render(request, 'blog/index.html', context)

模板

{% for post in posts %}
<div class="border p-3 mb-3">
    <div class="media">
    <img class="img-fluid rounded-circle border m-2" style="width: 70px; height:70px;"
        src="{{post.author.profile.image.url}}" alt="User Photo">
      <div class="media-body">
        <h5><a class="text-primary" href="{% url 'detail' post.id %}">{{post.title}}</a></h5>
          <h6 class="text-dark">Auther Score : {{******}}</h6>
        <p>{{post.content |truncatechars:150 }}
        <a class="text-primary" href="{% url 'detail' post.id %}">read more</a></p>
      </div>
    </div>
</div>
{% endfor %}

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    在您的 views.py 中,您正在渲染所有帖子。相反,我认为您可能需要呈现用户所有帖子的计数。 Getting a count of objects in a queryset in django 也检查此链接。这可能会有所帮助。

    【讨论】:

    • 感谢您的重播,但我在此页面尝试了答案,但并没有解决我的问题。你能写任何样本来研究它吗?感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多