私はユーザーに与えられたいいねの総数を取得しようとしています。私の場合は
author
投稿の。
うまくいかなかったので、私は自分の裁判についてコメントしました。
これがmodels.pyです
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
likes = models.ManyToManyField(User, related_name='liked', blank=True)
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
これが私が試したviews.pyです
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html"
def total_likes_received(request):
#total_likes_received = Post.likes.filter(author=request.user).count()
return render(request, 'blog/post_detail.html', {'total_likes_received': total_likes_received})
テンプレートは次のとおりです。
<small class="ml-5 mr-2" >Total {{ total_likes_received }} </small>
更新: これを修正しようとするために、私は追加しました:
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
total_likes_received = Post.likes.filter(author=self.request.user).count()
What should I add here to show the total likes of all posts of an author not the logged in user
context['total_likes_received'] = total_likes_received
私の質問は: 特定の著者に与えられたすべての投稿に与えられたいいねの総数を取得する方法
回答 4 件
次のクエリを使用してこれを行うことができると思います。
all_posts = request.user.author.all() total_likes_received = all_posts.aggregate(total_likes=Count('likes'))['total_likes']
次のように簡単にクエリできます。
total_likes_received = Like.objects.filter(post__author=self.request.user).count()
@A_K問題は、DetailViewを使用していることです。コードは適切ですが、あまり使用されていません。 答えは簡単で、コードを変更せずに次のようにします。
class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def total_likes_received(self): total_likes_received = Post.objects.filter(author=self.request.user).all() return total_likes_received.likes.count() def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = super(PostDetailView, self).get_context_data(**kwargs) context['total_likes_received'] = self.total_likes_received() return context
テンプレート内では、何も変更する必要はありません。
関連した質問
- DjangoAdminで多対多モデルのすべてのフィールドを表示するにはどうすればよいですか?
- Djangoフォームのドロップダウンのラベルを変更するにはどうすればよいですか?
- Djangoモデルフォームベースのシステムをサインアップ用の生のHTMLベースのフォームシステムに変換します
- Djangoで1対1のテーブルフィールド値にアクセスする
- DetailViewを介してURLパスを作成しようとしていますが、HTMLページで重複する値を取得しています
- Djangoのデフォルトのモデルフォームを使用せずに、Djangoの同じページで複数のフォームを処理する
- Django:フォームが無効な場合にフォームがリセットされないようにする
- Djangoは同じファイルでNameERRORをモデル化しますか?
- djangoチャネルを使用してPython36からPython37にアップグレードする際のSynchronousOnlyOperationエラー
- Django管理者の承認を得て登録するにはどうすればよいですか?
次の手順を実行して、post.authorのすべてのいいねを取得できます。