Search code examples
djangopython-3.xjoindjango-modelsdjango-2.1

Multiple join in django?


I have four models Quiz, Assignment, Question and Option in django 2.1. I want to retrieve Questions and options specific to a quiz. I tried with the code

**a=Quiz.objects.all() 
print(a[0].assignment_set.all())**

By using the above code am getting the assignment set:

[
{'id': 1, 'questionValue': 1, 'Question_id': 1, 'Quiz_id': 1}, 
{'id': 2, 'questionValue': 1, 'Question_id': 2, 'Quiz_id': 1}
] 

but i don't know how to get the respective options for the question.

My models

class Quiz(models.Model):
    name = models.CharField(max_length=30)
    type = models.CharField(max_length=30)
    openDate = models.DateField()
    closeDate = models.DateField()
    maxMarks= models.IntegerField()
    isActive= models.BooleanField()
    noOfAttempts=models.IntegerField()
    noOfQuestions=models.IntegerField()

class Question(models.Model):
    name = models.CharField(max_length=30)
    description=models.TextField()
    Category=models.ForeignKey(Category,on_delete=models.CASCADE)

class Option(models.Model):
    name = models.TextField()
    Question=models.ForeignKey(Question,on_delete=models.CASCADE)
    value= models.IntegerField()

class Assignment(models.Model):
    questionValue=models.IntegerField()   
    Question=models.ForeignKey(Question,on_delete=models.CASCADE)
    Quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE)

I want to get in the following format

"assignmentSet": [
      {
        "Question": {
          "id": "1",
          "name": "Q 1",
          "optionSet": [
            {
              "name": "option 1"
            },
            {
              "name": "Option 2"
            },
            {
              "name": "Option 3"
            },
            {
              "name": "Option 4"
            }
          ]
        }
      },
      {
        "Question": {
          "id": "2",
          "name": "Q 2",
          "optionSet": [
            {
              "name": "Option 1"
            },
            {
              "name": "Option 2"
            },
            {
              "name": "Option 3"
            },
            {
              "name": "Option 4"
            }
          ]
        }
      }]

Solution

  • Try this hear you will get a all options of Question

    class Question(models.Model):
        name = models.CharField(max_length=30)
        description=models.TextField()
        Category=models.ForeignKey(Category,on_delete=models.CASCADE)
    
        @property
        def options(self):
            return self.option_set.values()