首页 > 解决方案 > Django 将函数显示为带有模板标签的 html 中的列表

问题描述

鉴于我的两个模型,甲板和抽认卡:

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()

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

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

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

换句话说,我得到了正确的项目,只是格式不正确。我怎样才能将其作为“正常”列表?

例如,当我使用...

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

...有用。但是我不知道一个用户会有多少张卡,而且它当然效率不高。

我想做的是这样的:

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

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

我应该将此添加到我的视图中以使其正常工作吗?

标签: djangofilterdjango-querysettemplatetags

解决方案


你太接近了!

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

推荐阅读