class Like(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
3-在查看功能中,获取特定用户创建的帖子的所有赞:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Post, Like
@login_required
def popular_users(request):
# Get all the posts created by the current user
posts = Post.objects.filter(creator=request.user)
# Get all the likes on the current user's posts
likes = Like.objects.filter(post__in=posts)
# Count the number of likes for each user who liked the current user's posts
like_counts = {}
for like in likes:
user_id = like.creator.id
if user_id in like_counts:
like_counts[user_id] += 1
else:
like_counts[user_id] = 1
# Sort the users by the number of likes in descending order
popular_users = sorted(like_counts.items(), key=lambda x: x[1], reverse=True)
# Render the template with the popular users
return render(request, 'popular_users.html', {'popular_users': popular_users})
1条答案
按热度按时间brccelvz1#
您应该尝试发布您尝试发布的内容。如果没有上下文,此代码可能无法立即工作,请根据您的需要进行修改:
**假设您有一个模板 *'popular_users.html'*来显示受欢迎用户的列表。
1-定义“Post”模型,该模型具有指向“User”模型的外键,以便将每个帖子与其创建者关联起来:
2-定义“Like”模型,该模型具有指向“Post”模型的外键,用于将每个赞与其所属的帖子相关联,以及指向“User”模型的外键,用于将每个赞与创建它的用户相关联:
3-在查看功能中,获取特定用户创建的帖子的所有赞: