I am using Django rest framework I want to use random in my views.py can someone help me I want to make Questions in views.py to be random and here is my code
views.py
class QuizQuetionsList(generics.ListAPIView):
serializer_class=QuizQuetionsSerializer
def get_queryset(self):
quiz_id=self.kwargs['quiz_id']
quiz=models.Quiz.objects.get(pk=quiz_id)
return models.QuizQuetions.objects.filter(quiz=quiz)
class QuizChapterQuetionsList(generics.ListAPIView):
serializer_class=QuizQuetionsSerializer
def get_queryset(self):
quizChapter_id=self.kwargs['quizChapter_id']
quizChapter=models.QuizChapter.objects.get(pk=quizChapter_id)
return models.QuizQuetions.objects.filter(quizChapter=quizChapter)
this is my models.py
#Quiz Model
class Quiz(models.Model):
teacher=models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name='qize')
title=models.CharField(max_length=400)
detail=models.TextField()
add_time=models.DateTimeField(auto_now_add=True)
def __str__(self) :
return f"{self.teacher}-{self.title}"
class Meta:
verbose_name_plural="10.Quiz"
#QuizChapter Model
class QuizChapter(models.Model):
quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE,null=True)
title=models.CharField(max_length=400)
add_time=models.DateTimeField(auto_now_add=True)
def __str__(self) :
return f"{self.quiz}-{self.title}"
class Meta:
verbose_name_plural="11.QuizChapter"
#QuizQuetions Model
class QuizQuetions(models.Model):
quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE,null=True)
quizChapter=models.ForeignKey(QuizChapter,on_delete=models.CASCADE,null=True)
questions=models.CharField(max_length=400)
A=models.CharField(max_length=400)
B=models.CharField(max_length=400)
C=models.CharField(max_length=400)
D=models.CharField(max_length=400)
right_ans=models.CharField(max_length=400)
add_time=models.DateTimeField(auto_now_add=True)
def __str__(self) :
return f"{self.id}-{self.quizChapter}"
class Meta:
verbose_name_plural="12.QuizQuetions"
I want to make both of them to be random
to get solutions to my problem
CodePudding user response:
You can use order_by('?')
here for making the order of the queryset random, for example:
return models.QuizQuetions.objects.filter(quiz=quiz).order_by('?')