[英]How to display a Foreign Key in django template?
我的模板是這樣設置的:
{% for deck in deck %}
<a href='{% url 'deck_detail' deck.title %}'>
<li class='deckCards'>
<div class='deckText'>
<div class='deckTitle'>{{deck.title}}</div>
<div class='deckCreator'>{{deck.creator}}</div>
<div class='deckSubject'>{{deck.subject}}</div>
<div class='deckQuestion'>{{deck.questions.count}} Questions</div>
<div class='deckAccuracy'>{{The part I need help with}}%<div>
</div><!-- end of deckText -->
我的模型是這樣的:
class DeckAccuracy(models.Model):
deck = models.ForeignKey(Deck,
on_delete=models.CASCADE,
related_name='accuracy')
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='attempted_deck')
deck_accuracy = models.IntegerField(default=0)
num_of_attempts = models.IntegerField(default=0)
total_score = models.IntegerField(default=0)
def __str__(self):
return str(self.deck)
我的看法:
def DashboardView(request):
user = request.user
deck = Deck.objects.all()
return render(request, "cards/dashboard.html", {'deck': deck,
'user': user})
我不知道如何在模板的 for 循環中直接顯示甲板精度。 非常感謝你的幫助!
當您使用外鍵時,一副牌可以有不止一個牌組准確度記錄。 所以你需要遍歷deck.accuracy.all 數組。 所以應該這樣做:
<div class='deckAccuracy'>{% for acc in deck.accuracy.al%} {{acc}} {% endfor %}<div>
如果總是只有一個deckaccuracy,請使用OneToOneField,然后您可以使用deck.accuracy 來引用該值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.