Django ORM 查询 manytomany 字段以根据字典键输出列表

Django ORM query manytomanytofiled to output a list againist a dict key

我正在查询许多字段

这些是我的模型

class Choice(models.Model):
    choice_text = models.CharField(
        max_length=200
    )



class Question(models.Model):
    title = models.CharField(
        max_length=100
    )

    choices = models.ManyToManyField(
        Choice,
        through='QuestionChoice'
    )



class QuestionChoice(models.Model):
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE
    )
    choice = models.ForeignKey(
        Choice,
        on_delete=models.CASCADE
    )

我想得到所有 Question 及其所有选择

我的输出应该是这样的:

[
    {
        'title': 'a quetion title', 'choices': [
            {'id': 1,
            'choice_text': 'a choice text example'
            },
            {'id': 1,
            'choice_text': 'another text example'
            },
        ]
    },

    {
        'title': 'another quetion title', 'choices': [
            {'id': 1,
            'choice_text': 'a choice text example'
            },
            {'id': 1,
            'choice_text': 'another text example'
            },
        ]
    },
]

我不知道如何像这样获得上面的输出。

我的意思是,所有的选择都会在一个list of under the respected dict key choice.

如果你仔细看我的预期,你就会明白。

谁能帮助我完成它?

我试过如下:

Question.objects.all().values('title', 'choices')

但它returns重复的时间就像它有多少选择。

QList = [] #This is the final list
question_queryset = Question.objects.all() # This will get all the objects of Question model
for q in question_queryset:
    q_dict = {}
    q_dict['title'] = q.title
    q_dict['choices'] = []
    questionChoice_queryset = QuestionChoice.objects.filter(question=q) #This will basically get all those objects of QuestionChoice model where q is the value of "question" field in QuestionChoice model.
    for o in questionChoice_queryset:
        qChoice = o.choice.choice_text
        choice_dict = {'id':o.choice.id,'choice_text':qChoice}
        q_dict['choices'].append(choice_dict)
    QList.append(q_dict)