Python 如何通过预取显示多个相关对象?
更新 我能够在projectmodels.py中实现这一点,但我觉得这属于我的观点。我该怎么做呢?代码:Python 如何通过预取显示多个相关对象?,python,django,django-templates,views,django-orm,Python,Django,Django Templates,Views,Django Orm,更新 我能够在projectmodels.py中实现这一点,但我觉得这属于我的观点。我该怎么做呢?代码: @property def related_project_set(self): category_id_list = self.category.values_list("id", flat=True) return Project.live.filter(category__id__in=category_id_list).exclude(id=self.id)[:5]
@property
def related_project_set(self):
category_id_list = self.category.values_list("id", flat=True)
return Project.live.filter(category__id__in=category_id_list).exclude(id=self.id)[:5]
我想在项目的基于类的通用详细视图中显示按“类别”相关的“项目”。我还使用了Django括号预取相关的Mixin。但是我不明白为什么Python解释器显示的结果与我的模板不同 例如,给定db中的两个项目,我得到以下结果:
>>> from projects.models import Project
>>> Project.objects.all().prefetch_related('category')
[<Project: Avalon Road>, <Project: Piedmont Avenue>]
观点:
from __future__ import absolute_import
from braces.views import PrefetchRelatedMixin
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from .models import Project
from categories.models import Category
from testimonials.models import Testimonial
class ProjectDetailView(PrefetchRelatedMixin, DetailView):
prefetch_related = ['category']
queryset = Project.live.all()
def get_context_data(self, **kwargs):
"""
Allow the project detail view to display a list of testimonials.
"""
context = super(ProjectDetailView, self).get_context_data(**kwargs)
context['testimonial_list'] = Testimonial.displayed.all()
return context
class ProjectListView(ListView):
queryset = Project.live.all()
def get_context_data(self, **kwargs):
"""
Allow the project list view to display a list of categories.
"""
context = super(ProjectListView, self).get_context_data(**kwargs)
context['category_list'] = Category.objects.all()
return context
模板片段:
<ul>
{% for project in object.category.all %}
<li>{{ project.title }}</li>
{% endfor %}
</ul>
{object.category.all%中项目的%s}
- {{project.title}
{%endfor%}
您提到模板输出与shell不同,但没有显示模板结果。抱歉。以下是模板输出:- 厨房
。基本上,这是项目的类别,但不是通过该类别关联的项目。
<ul>
{% for project in object.category.all %}
<li>{{ project.title }}</li>
{% endfor %}
</ul>