英文:
How to access Foreign Fields in Django
问题
class Currency (models.Model):
currCode = models.CharField('货币',max_length=3)
currName = models.CharField('名称',max_length=100)
class Spend (models.Model):
spendAmount = models.DecimalField('金额', max_digits=12,decimal_places=2)
spendCurrency = models.ForeignKey(Currency)
英文:
I'm a beginner with Django. I have a set of tables with relationships defined in my models, and I am looking to retrieve linked values in the front end. I'm unable to find out how to do this, and would appreciate help.
I can currently see something that looks like this, where 1 is the key of the currency EUR in the Currency table:
Spend Amount | Spend Currency
10 | 1
I instead want it to look like this:
Spend Amount | Spend Currency
10 | EUR
Models
class Currency (models.Model):
currCode = models.CharField('Currency',max_length=3)
currName = models.CharField('Name',max_length=100)
class Spend (models.Model):
spendAmount = models.DecimalField('Amount', max_digits=12,decimal_places=2)
spendCurrency = models.ForeignKey(Currency)
Views
from .models import Spend
def all_spends(request):
spend_list = Spend.objects.all()
return render(request,
'spends/spend_list.html',
{'spend_list': spend_list})
HTML Template
{% for spend in spend_list %}
<tr>
<th>{{ spend.spendAmount }}</th>
<th>{{ spend.spendCurrency }}</th>
</tr>
{% endfor %}
答案1
得分: 1
直接从您的模板中,您可以使用外键字段直接访问您的货币模型,以显示所需的字段,在您的情况下是 Currency.currName 以显示:
在HTML模板中:
<table>
<thead>
<tr>
<th>Spend Amount</th>
<th>Spend Currency</th>
</tr>
</thead>
<tbody>
{% for spend in spend_list %}
<tr>
<td>{{ spend.spendAmount }}</td>
<td>{{ spend.spendcurrency.currName }}</td>
</tr>
{% endfor %}
</tbody>
</table>
请注意,还存在一种Django的“related manager”或“Backward relationship”方法来从Currency访问Spend。例如:
{{ my_currency.spend_set.spendAmount }}
英文:
Directly from your template, you can access directly your Currency model using the foreign key field to display the desired field, in your case Currency.currName to display:
Spend Amount | Spend Currency
10 | EUR
In HTML template
<table>
</thead>
<tr>
<th>Spend Amount</th>
<th>Spend Currency</th>
</tr>
</thead>
<tbody>
{% for spend in spend_list %}
<tr>
<td>{{ spend.spendAmount }}</td>
<td>{{ spend.spendcurrency.currName }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Note that it also exists a Django "related manager" or "Backward relationship" to access Spend from Currency. For example:
{{ my_currency.spend_set.spendAmount }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论