Django 显示函数作为 html 中带有模板标签的列表

Django display function as list in html with template tags

鉴于我的两个模型,Deck 和 Flashcard:

class Deck(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)

class Flashcard(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
question = models.TextField()
answer = models.TextField()

我想显示特定牌组的详细信息,例如该套牌的问题和答案列表。

所以在我的 Deck 模型中,我有以下功能:

def list_flashcards(self):
    fc_list = Flashcard.objects.filter(deck=self).values_list('question', flat=True)
    return fc_list

现在在我的 html 模板中,如果我使用:

{{deck.list_flashcards}}

我得到:<QuerySet ['first', 'second','third']

换句话说,我得到了正确的项目,只是格式不正确。我如何才能将其作为 'normal' 列表?

例如,当我使用...

{{deck.list_flashcards.0}} <br>
{{deck.list_flashcards.1}} <br>

...有效。但是我不知道用户会有多少张卡,当然效率也不高。

我想做的是这样的:

{% for fc in fc_list %}
  Question: {{fc}}
{% endfor %}

但它不起作用 - 网站上没有显示任何内容。

我是否应该将其添加到我的视图中才能使其正常工作?

你太接近了!

{% for card in deck.list_flashcards %}
  Question: {{card}}
{% endfor %}