django 想要获得受欢迎的用户

v9tzhpje  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(116)

我需要一个Django应用程序的帮助,所以我试图获得受欢迎的用户。我想通过获得特定用户创建的帖子的所有喜欢来存档。

brccelvz

brccelvz1#

您应该尝试发布您尝试发布的内容。如果没有上下文,此代码可能无法立即工作,请根据您的需要进行修改:

**假设您有一个模板 *'popular_users.html'*来显示受欢迎用户的列表。

1-定义“Post”模型,该模型具有指向“User”模型的外键,以便将每个帖子与其创建者关联起来:

class Post(models.Model):
    creator = models.ForeignKey(User, on_delete=models.CASCADE)
    # other fields for the post

2-定义“Like”模型,该模型具有指向“Post”模型的外键,用于将每个赞与其所属的帖子相关联,以及指向“User”模型的外键,用于将每个赞与创建它的用户相关联:

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})

相关问题