我在使用子项获取父项数据时遇到问题。
模型.py
class Company_Data(models.Model):
company_name = models.CharField(max_length=254)
company_address = models.CharField(max_length=254)
company_tel_no = models.CharField(max_length=254)
company_fax_no = models.CharField(max_length=254)
class Requirements(models.Model):
req_service = models.CharField(null=False, max_length=254)
req_coverdate_from = models.DateField()
req_coverdate_to = models.DateField()
req_duedates = models.DateField()
company = models.ForeignKey(Company_Data, on_delete=models.CASCADE)
View .py
def business_setup(request):
req = Requirements.objects.filter(req_service = 'Business Setup')
context = {
'req' : req ,
}
return render(request, 'admin_template/content/admin_businesssetup_req.html', context)
模板 HTML
{% for requirements in req %}
<table>
<tbody>
<tr>
<th style="width:50%">Company Name</th>
<td>{{ requirements.company_id.company_name }}</td>
</tr>
<tr>
<th> Covered Date From </th>
<td>{{ requirements.req_coverdate_from }}</td>
</tr>
<tr>
<th> Covered Date To </th>
<td>{{ requirements.req_coverdate_to }}</td>
</tr>
<tr>
<th> Due Date </th>
<td>{{ requirements.req_duedates }}</td>
</tr>
</tbody>
</table>
{% endfor %}
我尝试的是requirements.company_id.company_name
来显示相关的公司名称,但没有成功。我发现查询父 Company_Date
以显示子 Requirements
。但我想过滤 Requirements
表并显示它的父表,因此这些不适用于我。
谢谢你..
最佳答案
You just have to write "company" instead of "company_id" in your template
<td>{{ requirements.company.company_name }}</td>
关于python - Django:使用子外键获取父数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58785462/