I am trying to create a game that allows users to play a quiz, which is stored as a Django object, but I want the order of the questions to be different (as in random) every time. Is there a way to accomplish this?
models.py
class Quiz(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE, default="")
title = models.TextField(default="")
question1 = models.TextField()
answer1 = models.TextField()
question2 = models.TextField()
answer2 = models.TextField(default="")
question3 = models.TextField()
answer3 = models.TextField()
...
(The questions and answers go to 10.)
views.py
def quiz(request, quiz_id):
quiz = get_object_or_404(Quiz.objects, pk=quiz_id)
return render(request, "capstone/quiz.html", {
"quiz": quiz
})
I was thinking about generating a random number, but I think that would be too complicated with the number of questions. Is there any easier way to randomly display the questions to the user?
CodePudding user response:
Try to use a embedded ORM function.
Quiz.objects.order_by('?')
CodePudding user response:
The below will extract the questions from your queryset into a tuple containing the question and the question number, and then shuffle the tuples, putting them into their own context value
import random
def quiz(request, quiz_id):
quiz = get_object_or_404(Quiz.objects, pk=quiz_id)
#convert the queryset into a dict so we can get the questions
quiz_values = quiz.values()
quiz_questions = []
for i in range(1,11):
quiz_questions.append((i, quiz_values['question' str(i)]))
random.shuffle(quiz_questions)
return render(request, "capstone/quiz.html", {
"quiz": quiz, "quiz_questions": quiz_questions
})
Then in your template, you can refer to something like
{% for q in quiz_questions %}
{{q.1}} <!-- question text -->
<input type="text" name="id_question{{q.0}}"> <!-- question number -->
{% endfor %}
...so your form doesn't lose track of which question is being answered.