首页 > 解决方案 > 如何检索模板中链接到不同对象的对象?姜戈

问题描述

我有一个测验模型和一个视图,其中显示了页面上所有测验的列表。我想显示他们在每个测验旁边得到的分数。目前,我有一个分数模型,它链接到每个测验和参加测验的用户。我想做一些事情,比如Score.objects.filter(user=request.user, quiz=quiz).get_percentage()显示该测验的百分比。但是,这当然不适用于模板代码。

def learn(request): #Quiz Screen
    context = {
        'quizzes':Quiz.objects.all(),
        'scores':Score.objects.filter(user=request.user),
    }
    return render(request, 'quiz_app/learn.html', context)


{% extends "quiz_app/base.html" %}
{% block content %}
    <a href="{% url 'quiz-create' %}">New Quiz</a>
    {% for quiz in quizzes %}
        <a id="quiz-anchor" href="{% url 'quiz-detail' quiz.id %}">
            <article class="quiz-thumbnail-large">
                <h2>{{ quiz.title }}</h2>
                <h3>{{ quiz.question_amount }} Questions</h3>
                <p>Score: {{ quiz.score.get_percentage }}%</p>
            </article>
        </a>
    {% endfor %}
{% endblock content %}
class Quiz(models.Model):
    title = models.CharField(max_length=100) #or TextField
    #slug = models.SlugField(max_length=200, default=1) #url
    video_link = models.CharField(max_length=100, default="https://www.youtube.com/watch?v=p60rN9JEapg")
    question_amount = models.IntegerField()
    author = models.ForeignKey(User, default=1, on_delete=models.CASCADE, related_name='quiz_author',)
    date_created = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name_plural = "Quizzes"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('quiz-detail', kwargs={'pk': self.pk})


class Score(models.Model):
    quiz = models.ForeignKey(Quiz, default=1, on_delete=models.CASCADE)
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    correct_answers = models.IntegerField()
    incorrect_answers = models.IntegerField()

    def __str__(self): #returns as a/b
        score = str(self.correct_answers) + '/' + str(self.get_total_answers())
        return score

    def add_correct_answers(self, amount):
        self.correct_answers = self.correct_answers + amount
        self.save()

    def add_incorrect_answers(self, amount):
        self.incorrect_answers = self.incorrect_answers + amount
        self.save()

    def get_total_answers(self):
        total = self.correct_answers + self.incorrect_answers
        return total

    def get_percentage(self):
        percentage = round(self.correct_answers / self.get_total_answers() * 100)
        return percentage

标签: pythondjangoobjectdjango-templatesdjango-views

解决方案


因此,由于和之间有外键关系,因此单个测验可以有多个分数,因此您应该使用模型中的反向关系,如下所示:QuizScorequiz

{% extends "quiz_app/base.html" %}
{% block content %}
    <a href="{% url 'quiz-create' %}">New Quiz</a>
    {% for quiz in quizzes %}
        <a id="quiz-anchor" href="{% url 'quiz-detail' quiz.id %}">
            <article class="quiz-thumbnail-large">
                <h2>{{ quiz.title }}</h2>
                <h3>{{ quiz.question_amount }} Questions</h3>
                {% for score in quiz.score_set.all %}
                    <p>Score: {{ score.get_percentage }}%</p>
                {% endfor %}
            </article>
        </a>
    {% endfor %}
{% endblock content %}

编辑

这是一个快速修复:

{% extends "quiz_app/base.html" %}
{% block content %}
    <a href="{% url 'quiz-create' %}">New Quiz</a>
    {% for quiz in quizzes %}
        <a id="quiz-anchor" href="{% url 'quiz-detail' quiz.id %}">
            <article class="quiz-thumbnail-large">
                <h2>{{ quiz.title }}</h2>
                <h3>{{ quiz.question_amount }} Questions</h3>
                {% for score in quiz.score_set.all %}
                    {% if score.user == request.user %}
                        <p>Score: {{ score.get_percentage }}%</p>
                    {% endif %}
                {% endfor %}
            </article>
        </a>
    {% endfor %}
{% endblock content %}

但这不是一个好主意,因为您将首先检索所有用户的所有分数,然后对其进行过滤;这里最好使用模板标签。


推荐阅读