bugfix> django > 投稿


  1. views.py - Here I have put all my posts in all_posts and then has looped through the posts to get the count of total likes on this post from a Likes table in the model (If there is a better way please suggest) into the likes dictionary.
all_posts = NewsFeed.objects.all().order_by('time').reverse()
likes = {}
for post in all_posts:
    likes_count = Likes.objects.filter(newsfeed = post).count()
    likes[post.id] = likes_count
form = StatusForm()
context = {
    'name': name,
    'all_posts': all_posts,
    'statusForm': form,
    'likes': likes,

  1. index.html - Here I want to display all the posts and a like button for each post which would also display the number of likes on the post. When I am manually trying to access the likes count {{ likes.4 }} it is displaying correct count for the fourth status Like(1) but when I try to access it like {{ likes.post_id }} it displays nothing Like(). Please help me out as I am new to this and also provide with the suggestions to do the same in a better way if there's any.
{% for post in all_posts %}
<div class="newsfeed-div">
    <h3>{{ post.title }}</h3>
    <p>{{ post.content }}</p>
    <pre>{{ post.user.name }}</pre>
    <pre>{{ post.time }}</pre>
    {% with post_id=post.id %}
        <a href="{% url 'newsfeed:likeStatus' post.id %}"><button>Like({{ likes.post_id }})</button></a>
        <a href="#"><button>Comment(0)</button></a>
    {% endwith %}
{% endfor %}




回答 1 件
  • Djangoテンプレートは、変数キーによるインデックス作成をサポートしていません。同様の質問については、テンプレートのディクショナリ値にアクセスできない(オブジェクトpkがdictキーです)をご覧ください。


    {{ post.likes_set.count }}

    ザ・ _set  接尾辞は、 RelatedManager のデフォルト名の規則です  これは、1対多の関係ですべての子レコードを返します(すべての likes  特定の post に属する  この例では)および .count  行数を返します。