我正在制作一个简单的应用程序,您可以在其中对不同的帖子投反对票和赞成票。我在 Python/Django 中构建它...我通过将用户 id 和评论 id 存储到 Upvote 模型中来获取赞成票/反对票计数,并通过关联得到计数 1。它打印出正确的数字查看除了打印出被投票的次数之外的计数。例如,如果它是 1,它将打印:1,但如果它是 3,它将打印:3 3 3。我如何更改我的逻辑,以便它只打印一次数字?
查看页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Topic</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<a href="/dashboard">Dashboard</a>
<a href="/logout">Logout</a>
<hr>
<a href="/users/{{topic.user.id}}/">{{topic.user.first_name}} </a>posted a topic:
<hr>
Topic: {{topic.topic}}
<br>
Description: {{topic.description}}
<hr>
<h3>Post your answer</h3>
<form action="/topic/{{topic.id}}/post" method="post">
{%csrf_token%}
<textarea name="comment" id="" cols="20" rows="2" required style="resize:none"></textarea>
<br>
<input type="submit" value="Post">
</form>
<hr>
{% for comment in comments %}
<a href="/users/{{comment.user_id}}/">{{comment.user.first_name}}</a>: {{comment.comment}}
<br>
<a href="/delete/{{comment.id}}/">Delete Post</a>
<h5>Number of upvotes:</h5>
{% for upvote in upvotes %}
{% if upvote.comment_id == comment.id %}
{{upvotes.count}}
{%endif%}
{%endfor%}
<h5>Number of downvotes: </h5>
{% for downvote in downvotes %}
{% if downvote.comment_id == comment.id %}
{{downvotes.count}}
{%endif%}
{%endfor%}
<hr>
<a href="/upvote/{{comment.id}}/"><button>Upvote</button></a>
<a href="/downvote/{{comment.id}}/"><button>Downvote</button></a>
<br>
<form action="/idea/{{comment.id}}/" method="post">
{%csrf_token%}
<textarea name="idea" id="" cols="20" rows="2" required style="resize:none"></textarea>
<br>
<input type="submit" value="Comment">
</form>
{% for idea in ideas %}
{% if idea.comment_id == comment.id %}
<a href="/users/{{idea.user_id}}/">{{idea.user}}</a>
says: {{idea.idea}}
<a href="/delete/{{idea.id}}/comment">Delete Comment</a>
{%endif%}
{%endfor%}
{%endfor%}
</div>
</body>
</html>
最佳答案
给定您的代码
{% for upvote in upvotes %}
{% if upvote.comment_id == comment.id %}
{{upvotes.count}}
{%endif%}
{%endfor%}
您最终打印了 upvotes.count
次 upvotes
次。您可以完全摆脱整个 for 循环,只需使用 {{upvotes.count}}
。
关于python - 如何在Python中获取唯一计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33506383/