用户名未显示,但用户 ID 显示在 Django 的 html 模板中

Username is not showing but user id is showing in html template in Django

下面是我的模型:

class Problem_Solved(models.Model):
    user_ref = models.ForeignKey(User, on_delete=models.CASCADE)
    contest_ref = models.ForeignKey(Contest, on_delete=models.CASCADE)
    problem_ref = models.ForeignKey(Problem, on_delete=models.CASCADE)
    points_get = models.IntegerField(default=0)
    time_submitted = models.DateTimeField('date published')
    
    class Meta:
        unique_together = (("user_ref", "problem_ref"))
        

    def __str__(self):
        return self.user_ref.username + " solved " + self.problem_ref.problem_name + " and got " + str(self.points_get) + " marks " 

下面是我的视图函数:

def pointtable(request, contest_id):
    context = {}
    contest_obj=Contest.objects.get(pk=contest_id)
    points_list = Problem_Solved.objects.filter(contest_ref = 
      contest_obj).values('user_ref').annotate(user_sum = Sum('points_get')).order_by('-user_sum')
    print(points_list)
    context['points_list'] = points_list
    return render(request,'leaderboard.html', context)

下面是我的 html 代码:

{% for pt in points_list %}
            <div class="container-sm w-75  tb-bg-color">
                <div class="row mb-3 ">
                    <div class="col-1 themed-grid-col col-border">{{forloop.counter}}</div>
                    <div class="col-6 themed-grid-col col-border">{{pt.user_ref.username}}</div>
                    <div class="col-2 themed-grid-col col-border">{{pt.user_sum}}</div>
                </div>
            </div>
    {% endfor %}

下面是输出:

Username is not showing

如图所示,用户名未显示,但如果我在 html 代码中写入 pt.user_ref,它将打印 user_id,如下所示:

User id is showing

现在我想要用户名而不是用户 ID 我应该怎么做,因为我从 2 天开始就一直坚持这个问题。如果可以的话,请帮助我。

由于您希望每个用户的积分统计改为在 User 模型上进行注释,因此您将获得 User 对象的 QuerySet,因此您可以简单地获取用户名:

def pointtable(request, contest_id):
    context = {}
    contest_obj=Contest.objects.get(pk=contest_id)
    contest_users = User.objects.filter(
        problem_solved__contest_ref = contest_obj
    ).annotate(
        point_sum=Sum('problem_solved__points_get')
    ).order_by('-point_sum')
    context['contest_users'] = contest_users
    return render(request,'leaderboard.html', context)

现在您的 html 将是:

{% for contest_user in contest_users %}
    <div class="container-sm w-75  tb-bg-color">
        <div class="row mb-3 ">
            <div class="col-1 themed-grid-col col-border">{{forloop.counter}}</div>
            <div class="col-6 themed-grid-col col-border">{{contest_user.username}}</div>
            <div class="col-2 themed-grid-col col-border">{{contest_user.point_sum}}</div>
        </div>
    </div>
{% endfor %}

Note: Class names should not have underscores in them. So ProblemSolved instead of Problem_Solved