我在 MySQL DB 中有以下示例表与 Django 交互
class Env(models.Model):
name = models.CharField()
class ExecutionDetail(models.Model):
executionid= models.ForeignKey(Execution)
job= models.CharField()
class Execution(models.Model):
name= models.ForeignKey(Env)
executionid= models.CharField()
envname= models.ForeignKey(Env)
我使用视图选择数据
def v_job_history(request, job):
logger.debug("Calling history jobs")
jobname=job
myjobs = ExecutionDetail.objects.filter(job=job)
template = loader.get_template('history_jobs.html')
context = {
'myjobs': myjobs,
}
return HttpResponse(template.render(context, request))
然后在我的 HTML 中尝试显示我的数据,例如
{% for x in myjobs %}
<tr>
<td>{{ x.execution.envname}} </a></td>
<td>{{ x.execution.name }} </a></td>
<td>{{ x.job}}</td>
</tr>
{% endfor %}
问题是 x.execution.env_name 将返回环境对象 (2) 等
我尝试过 x.execution.env_name - 返回对象。 x.env.name、x.execution.env.name 不返回任何内容。
我建议给
ForeignKey
更好的名字,.executionid
是不是Execution
的id,它是一个Execution
对象,所以:
class Env(models.Model):
name = models.CharField(max_length=128)
class ExecutionDetail(models.Model):
execution = models.ForeignKey(Execution, on_delete=models.CASCADE)
job = models.CharField()
class Execution(models.Model):
name = models.ForeignKey(Env)
executionid = models.CharField(max_length=128)
env = models.ForeignKey(Env, on_delete=models.CASCADE)
然后你可以使用:
{% for x in myjobs %}
<tr>
<td>{{ x.execution.env.name }}</a></td>
<td>{{ x.execution.name }} </a></td>
<td>{{ x.job }}</td>
</tr>
{% endfor %}
并通过以下方式提高效率:
def v_job_history(request, job):
logger.debug('Calling history jobs')
jobname = job
myjobs = ExecutionDetail.objects.filter(job=job).select_related(
'execution__env'
)
context = {
'myjobs': myjobs,
}
return render(request, 'history_jobs.html', context)