Python 在模板中显示Django ForeignKey值
我试图在模板中显示模型的ForeignKey值,所有其他字段都显示良好,但我无法使其正常工作。这是我的密码: models.py:Python 在模板中显示Django ForeignKey值,python,django,Python,Django,我试图在模板中显示模型的ForeignKey值,所有其他字段都显示良好,但我无法使其正常工作。这是我的密码: models.py: class BodyPart(models.Model): body_part = models.CharField(max_length=20, unique = True) class Exercise(models.Model): body_part = models.ForeignKey(BodyPart, on_delete=models
class BodyPart(models.Model):
body_part = models.CharField(max_length=20, unique = True)
class Exercise(models.Model):
body_part = models.ForeignKey(BodyPart, on_delete=models.CASCADE, default = "bodypart", related_name="bodypart")
views.py:
exercises = Exercise.objects.filter(category=exercisedetailcategory).values()
context = {
"exercises" : exercises,
}
return render(request,"exercises-categories.html",context)
模板:
{% for exercise in exercises %}
<span class="post-meta-category"><a href="">{{exercise.body_part}}</a></span>
<div class="post-item-description">
<a href="">{{exercise.title}}</a>
<p>{{exercise.content}}</p>
{% endfor %}
{%用于练习中的练习%}
{{exercise.content}
{%endfor%}
这是您不应该使用.values()
的众多原因之一。如果传递练习
模型,则可以将相关对象提取到内存中。您可以使用。选择\u related(..)
以优化查询:
exercises = Exercise.objects.filter(
category=exercisedetailcategory
).select_related('body_part')
context = {
'exercises' : exercises,
}
return render(request, 'exercises-categories.html', context)
然后,在模板中,我们可以使用以下方式渲染:
{% for exercise in exercises %}
<span class="post-meta-category"><a href="">{{ exercise.body_part.body_part }}</a></span>
<div class="post-item-description">
<a href="">{{ exercise.title }}</a>
<p>{{ exercise.content }}</p>
{% endfor %}
{% for exercise in exercises %}
<span class="post-meta-category"><a href="">{{ exercise.body_part }}</a></span>
<div class="post-item-description">
<a href="">{{ exercise.title }}</a>
<p>{{ exercise.content }}</p>
{% endfor %}
然后使用以下命令渲染此内容:
{% for exercise in exercises %}
<span class="post-meta-category"><a href="">{{ exercise.body_part.body_part }}</a></span>
<div class="post-item-description">
<a href="">{{ exercise.title }}</a>
<p>{{ exercise.content }}</p>
{% endfor %}
{% for exercise in exercises %}
<span class="post-meta-category"><a href="">{{ exercise.body_part }}</a></span>
<div class="post-item-description">
<a href="">{{ exercise.title }}</a>
<p>{{ exercise.content }}</p>
{% endfor %}
{%用于练习中的练习%}
{{exercise.content}}
{%endfor%}
在您的练习模型中,忽略默认部分。(可以显示任何告诉用户“没有身体部位”的消息,例如
{%if not exercise.body_part%}->没有要显示的内容)
并确保您的exercise.body\u part中有一个值,这意味着您的BodyPart模型中必须有一个与此模型的当前对象相关的对象
它也应该是{{exercise.body_part.body_part}}
第二个是提取相关BodyPart对象值的值@EmreAylanc:您从查询中删除了
.values()
?到底发生了什么?展示什么?为{{exercise.body\u part.body\u part}}
呈现什么?.select\u related()
是一种很好的做法,有助于创建更高效的代码。但是,如果性能不是您的问题(即,您只是在学习),您可以避免。从查询中选择{u related('body\u part')
,您将可以访问Willem建议的相关对象{{exercise.body\u part.body\u part}
。