如何在Djang中从下面的模型中获得choice\u文本值

2024-05-07 23:40:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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']

如何做到这一点?你知道吗


Tags: django答案textanswer模型falsemodelmodels
3条回答

您可以使用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'

希望有帮助。你知道吗

另一种选择:

correct_answer = []
for i in question:
    correct_answer.append(Choice.objects.get(question=i, answer=True).choice_text)

如果您只需要一个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的文档

相关问题 更多 >