我试图显示一个查询到模板,我得到了正确的数据输出,但它是用Queryset<>标签显示,我相信这是使用的原因。所有在我的模板进行查询,但我无法弄清楚我将如何显示信息与使用。所有
models.py
class SectionMeetingDate(models.Model):
section_date = models.DateField()
# time stamps when a cost center is created or updated
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.section_date)
class SectionMeeting(models.Model):
user = models.CharField(max_length=200)
section_meeting_date = models.ManyToManyField(SectionMeetingDate, related_name='section_meeting_date')
# time stamps when a cost center is created or updated
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user)
class CostCenterID(models.Model):
name = models.CharField(max_length=200)
dept_leader = models.CharField(max_length=200, null=True, blank=True)
section_leader = models.ManyToManyField(SectionMeeting, related_name='section_leader')
department_meeting = models.ManyToManyField(DepartmentMeeting, related_name='section_leader')
# time stamps when a cost center is created or updated
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
views.py
def cost_center_id(request, pk):
# provides the name of the section leaders for each cost center ID
names = CostCenterID.objects.get(id=pk)
context = {
'names':names,
}
return render(request, 'DeptSummary/cost_center_id.html', context)
cost_center_id.html
{% for section_leaders in names.section_leader.all %}
<h5>
Section Leader --
<a href="{% url 'section_leader_date' section_leaders.id %}">
{{ section_leaders }}
</a>
-- Total -- {{section_leaders.section_meeting_date.count}}
-- {{section_leaders.section_meeting_date.all}}
</h5>
{% endfor %}
当前我的模板正在显示:部门负责人--阿尔宾Ortiz --总计-- 1 -- <QuerySet [<SectionMeetingDate: 2023-05-08>]>
我想要的是部门负责人--阿尔宾Ortiz --总计-- 1 -- 2023-05-08
我试过用几种不同的方法重写我的查询,但无法弄清楚如何在没有QuerySet标记的情况下显示我的信息。
1条答案
按热度按时间ttcibm8c1#
我进一步建议预取
section_leader
s和它们的section_meeting_date
s,以防止 N+1 问题:注意:通常使用**
get_object_or_404(…)
[Django-doc]比直接使用.get(…)
**[Django-doc]更好。如果对象不存在,例如因为用户自己更改了URL,则get_object_or_404(…)
将导致返回 HTTP 404 Not Found 响应,而使用.get(…)
将导致 HTTP 500 Server Error。