1

我在 Django 中有这样的模型:

class Choice(models.Model):

    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=150)
    answer = models.BooleanField(blank=False, default=False)

我在这样的列表中有一个问题:[1, 2]

现在,我想得到那个的正确答案question。所以,我喜欢这样:

>>> for i in question:
...     Choice.objects.filter(question=i, answer=True)
... 
[<Choice: yes>]
[<Choice: ok1>]

相反,我希望正确答案出现在列表中,例如:

correct_answer = ['yes', 'no']

如何做到这一点?

4

3 回答 3

0

您可以使用in. 然后迭代结果并查看是否choice_text等于yes

choices = Choice.objects.filter(question_id__in=[1,2], answer=True)
for choice in choices:
    print choice.question_id, choice_text if choice_text == 'yes' else 'no'

希望有帮助。

于 2013-09-18T11:38:08.807 回答
0

另外的选择:

correct_answer = []
for i in question:
    correct_answer.append(Choice.objects.get(question=i, answer=True).choice_text)
于 2013-09-18T11:40:39.823 回答
0

如果您想要一个仅包含 的平面列表,choice_text则可以.values_list()flat=True参数一起使用。例如:

correct_answer = Choice.objects.filter(question=i, answer=True).values_list('choice_text', flat=True)
# correct_answer will be ['yes', 'no'] or whatever the choice_text's are.

以下是有关文档.values_list()https ://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

于 2013-09-18T11:53:01.153 回答