【问题标题】:How to get the choice_text value from the following model in Django如何从Django中的以下模型中获取choice_text值
【发布时间】:2013-09-23 03:34:12
【问题描述】:

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

如何做到这一点?

【问题讨论】:

    标签: python django list django-queryset


    【解决方案1】:

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

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      另一种选择:

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

      【讨论】:

        【解决方案3】:

        如果您只想要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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-05
          • 2018-10-15
          • 1970-01-01
          • 2016-01-02
          • 1970-01-01
          • 2020-07-07
          • 2011-10-07
          • 1970-01-01
          相关资源
          最近更新 更多