0

I am a fresh learner of django framework.

I am trying to develop a learning portal, whereas every topic will have its own quiz. My models are as follows:

class Quiz(models.Model):
    title = models.CharField(max_length=255)
    book_name = models.CharField(max_length=255)
    slug = models.SlugField(blank = True)
    topic = models.CharField(max_length=255)
    number_of_questions = models.IntegerField()
    
    class Meta:
        verbose_name_plural = 'Quizes'
        
    def __str__(self):
        return self.title
   

my question model is as follows:

class Quest(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete= models.CASCADE)
    question_text = models.CharField(max_length=500)
    option_1 = models.CharField(max_length=250)
    option_2 = models.CharField(max_length=250)
    corr_ans = models.CharField(max_length=250)
    
       
    def __str__(self):
        return self.question_text
    
    class Meta:
        verbose_name_plural = 'Questions'

my view is as under:

def questions(request, url):
    questions = Quiz.quest_set.filter(slug = url)
    return render(request, 'quiz/questions.html', {'questions': questions})

Every quiz has multiple quest (questions). I want to call the questions by using quiz slug.

Django is showing me an error "'ReverseManyToOneDescriptor' object has no attribute 'filter'".

I tried and search a lot, however, could not figured it out, how to throw the questions via using quiz slug i.e. reverse look up.

I have also referred the following stackoverflow's link [https://stackoverflow.com/questions/15306897/django-reverse-lookup-of-foreign-keys][1]

What would be the best way to get questions related to a particular quiz and view it on the page, as every book will have multiple quizzes, and to avoid the afore-mentioned error.

Thanks for your time and support.

Regards Syed

1 Answers1

0

You should do the following query:

questions = Quiz.objects.get(slug=url).quest_set.all()

What you're doing above is:

  • Get the Quiz based on the given slug: Quiz.objects.get(slug=url)
  • Get all related questions: .quest_set.all()
Michael Anckaert
  • 853
  • 8
  • 12