django - 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 %}
但它不起作用 - 网站上没有任何内容。
我应该将此添加到我的视图中以使其正常工作吗?
解决方案
你太接近了!
{% for card in deck.list_flashcards %}
Question: {{card}}
{% endfor %}
推荐阅读
- firebase - 阻止禁用的用户 Firebase 规则
- javascript - 如果 heaptotal / heapused 很低,我应该担心节点中的高 RSS 吗?
- java - 如何基于 XML 文件生成签名?
- mule - 安装 Anypointstudio 时无法创建 JVM
- file - Flutter 如何在 iPhone 上保存通过 getApplicationDocumentsDirectory() 创建的文件?
- python - 我应该为正则表达式编写什么查询来捕获指定的段落格式并跳过其余部分?
- reactjs - 有没有办法先在选项卡之间同步 redux 存储状态,然后让每个选项卡控制自己的状态?
- javascript - How can i merge two arrays in one array of arrays in Javascript?
- ruby-on-rails - Rails find_by_sql 返回带有空对象的数组
- testing - 有没有办法在clojure中模拟一个函数?