如何从Django视图返回单独模型的单个列表

时间:2019-04-17 16:36:12

标签: django database class django-views

我正在为拼写网站创建排行榜系统,我需要显示得分最高的10个用户以及当前访问该网站的用户的列表。当我调用context_object_name模板时,单独的列表起作用。我可以显示前10名用户,也可以显示登录的用户,但是当我尝试显示这两个用户时都会失败。我该怎么办?

views.py-该用户正以“ id = 10”列出,以进行故障排除:

from .models import Profile, User
from django.http import HttpResponse,HttpResponseRedirect, Http404
from django.views.generic import ListView, TemplateView
from django.shortcuts import get_object_or_404, render
from django.urls import reverse


class Homepage(ListView):
    template_name='homepage.html'
    context_object_name = 'profile_list'
    def get_queryset(self):
       return (Profile.objects.order_by('-score')[:10], 
              User.objects.get(id=10).profile)

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  played = models.BooleanField(default=False)
  mistake = models.CharField(max_length=120, default="", blank=True)
  score = models.IntegerField(default=0)
  outOf = models.IntegerField(default=0)
  percentCorrect = models.CharField(max_length=120, default="n/a")

  def __str__(self):
    return self.user.username;

homepage.html的相关部分:

{% if profile_list %}
  <h1 id=ldbtitle>Leaderboard:</h1>
  <ul id=ldb>
    <li id=ldbfields>
      <div id=ldb1>
        <p>Username</p>
      </div>
      <div id=ldb2>
        <p>Score</p>
      </div>
    </li>
    {% for Profile in profile_list %}
      <li id=ldbitems>
        <div id=ldb1>
          <p id=1>{{Profile.user.username}}</p>
        </div>
        <div id=ldb2>
          <p>{{ Profile.score}}/{{Profile.outOf}}</p>
        </div>
      </li>
    {% endfor %}
  </ul>
{% else %}
  <p>No users are available.</p>
{% endif %}

0 个答案:

没有答案