Home > database >  Query M2M relations in Django
Query M2M relations in Django

Time:08-04

I've the following model:

class Quiz(models.Model):
    name = models.CharField(max_length=255)
    month = models.DateField()

class Question(models.Model):
    title = models.CharField(max_lenght=255)
    category = models.CharField(max_length=255)
    status = models.CharField(max_length=255, status=(('Pending', 'Pending'), ('Approved', 'Approved'))

class Contest(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    questions = models.ManyToManyField(Question, related_name='contest_questions')

Now I want to get list of quizes with all questions whose status=Pending?

Any help would be much appreciated!

CodePudding user response:

Another approach is query directly from the M2M table using values_list():

quiz_ids = list(Contest.objects.filter(questions__status='Pending').values_list('quiz__id', flat=True))

quiz_query = Quiz.objects.filter(id__in=quiz_ids)
  • Related