我可以在Django 1.10的模板中显示其他表中的字段吗?
我有3个表格,如下面的models.py
import datetime
from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Group(models.Model):
group_name = models.CharField(max_length=255)
no_of_monk = models.IntegerField()
def __str__(self):
return self.group_name
class Meta:
ordering = ['id']
@python_2_unicode_compatible
class Tbl_Province(models.Model):
province_code = models.CharField(max_length=2)
province_name = models.CharField(max_length=150)
geo_id = models.IntegerField()
def __str__(self):
return self.province_name
@python_2_unicode_compatible
class Contact(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
order = models.IntegerField()
name = models.CharField(max_length=255, db_index=True)
description = models.TextField(blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
confirm = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
province = models.ForeignKey(Tbl_Province, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Meta:
ordering = ['order', 'province']
我希望在以下模板中显示tbl_province.province_name,其中id = contact.id,是否可能?
{% for contact in group.contact_set.all %}
<tr>
<td width="10%" class="table-text"><div><strong>{{ forloop.counter0|mod:5|add:1 }}</strong></div></td>
<td width="10%" class="table-text"><div>{{ forloop.counter }}</div></td>
<td width="10%" class="table-text"><div>{{ contact.order }}</div></td>
<td class="table-text"><div>{{ contact.name }}</div></td>
{% if contact.province_id %}
<td class="table-text"><div>{{ **Want to display tbl_province.province_name where id=contact.id here** }}</div></td>
{% endif %}
<td width="13%" class="table-text"><div><input type="text" name="ord" id="con-ord" class="form-control" value="{{ contact.amount|intcomma }}"></div></td>
<td width="10%" class="table-text"><div>บาท</div></td>
<td>
<form action="{% url 'contribution:contactdel' contact.id %}" method="POST">
{% csrf_token %}
<button type="submit" id="delete-group" class="btn btn-danger">
<i class="fa fa-btn fa-trash"></i> Delete
</button>
</form>
</td>
</tr>
{% endfor %}
答案 0 :(得分:0)
模板无法访问数据库,因此无法执行查询(基本上是您想要的)
但是,我可以看到Tbl_Province
中有Contact
的外键,你可以使用它 - 只需写{% contact.province.province_name %}
(如果我正确理解了你的内容)。重新尝试实现)
如果您需要更具异国情调的东西,您必须在视图功能中执行查询,然后将其传递给模板上下文。