0
我有一個名爲電路的模型,每個電路可能有許多與之關聯的文件。Django模板 - 在模板中獲取匹配的外鍵對象?
所以在我看來我得到所有的電路和所有文件,然後我試圖讓文件匹配我的模板中使用if語句的電路。
我已經試過了,下面但是都回來了空,我如何遍歷模板中的模型來找到匹配?
file.circuit_contract_data
file.circuit_contract_data__id
感謝
view.py
@login_required
def showroom_detail(request, showroom_id):
modelShowroom = get_object_or_404(ShowroomConfigData, pk=showroom_id)
modelCircuits = CircuitInfoData.objects.filter(showroom_config_data=showroom_id)
modelCircuitFiles = CircuitFiles.objects.filter(circuit_contract_data__showroom_config_data=showroom_id)
modelSitePhotos = SitePhotos.objects.filter(showroom_config_data=showroom_id)
modelSiteFiles = SiteFiles.objects.filter(showroom_config_data=showroom_id)
return render(request, 'service/showroom_detail.html', {
'Showroom': modelShowroom,
'Circuits': modelCircuits,
'CircuitFiles': modelCircuitFiles,
'SitePhotos': modelSitePhotos,
'SiteFiles': modelSiteFiles,
})
模板
{% for item in Circuits %}
<tr class="{% cycle 'tr-1' 'tr-2' %}">
<td>{{ item.provider }}</td>
<td>{{ item.service_type }}</td>
<td>{{ item.circuit_speed }}</td>
<td>
{% for file in CircuitFiles %}
{% if file.circuit_contract_data == item.id %}
<a href ="{{ MEDIA_URL}}{{ file.circuit_file }}" target="_blank">{{ file.file_name }}</a><br />
{% endif %}
{% endfor %}
</td>
</tr>
模型
class CircuitInfoData(models.Model):
showroom_config_data = models.ForeignKey(ShowroomConfigData,verbose_name="Install Showroom",blank=True)
major_site_info = models.ForeignKey(MajorSiteInfoData,verbose_name="Install Site",blank=True)
service_type = models.ForeignKey(CircuitTypeInfoData)
circuit_speed = models.IntegerField(blank=True)
circuit_bearer = models.IntegerField(blank=True)
provider = models.CharField(max_length=200)
ref_no = models.CharField(max_length=200,verbose_name="Reference No")
install_location = models.CharField(max_length=200)
install_date = models.DateField()
cost_per_month = models.DecimalField(decimal_places=2,max_digits=8)
contract_length = models.IntegerField(verbose_name="Contact length in years")
notes = models.TextField(blank=True)
service_service_contacts = models.ForeignKey(ServiceContacts)
class Meta:
verbose_name = "Circuit Data"
verbose_name_plural = "Circuit Data"
ordering = ('showroom_config_data__location',)
def __unicode__(self):
return '%s | %s | %s | %s' % (self.showroom_config_data.location, self.provider, self.service_type, self.ref_no)
class CircuitFiles(models.Model):
circuit_contract_data = models.ForeignKey(CircuitInfoData,verbose_name="Showroom",blank=True)
circuit_file = models.FileField(blank=True,upload_to=service_upload_path)
file_name = models.CharField(max_length=200,verbose_name="File Name")
class Meta:
verbose_name = "Circuit Files"
verbose_name_plural = "Circuit Files"
ordering = ('circuit_contract_data',)
def __unicode__(self):
return self.file_name
謝謝,你是指模型或模板中的駱駝案件?我是否應該使用它? – AlexW
在模板中。約定是將其用於類定義,而對變量使用小寫。 – solarissmoke