如何通过prefetch_related显示通过ManyToMany相关的对象?

时间:2014-02-26 20:43:07

标签: python django django-templates views django-orm

更新 我能够在我的Project models.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]

我想在项目的基于类的基于类的详细信息视图中显示与“category”相关的“项目”。我也在使用Django-Braces PrefetchRelated Mixin。但我不明白为什么Python解释器显示的结果与我的模板不同。

例如,给定db中的两个项目,我得到以下结果:

>>> from projects.models import Project
>>> Project.objects.all().prefetch_related('category')
[<Project: Avalon Road>, <Project: Piedmont Avenue>]

型号:

class Project(models.Model):
    """
    A project completed by ICON.

    """
    LIVE_STATUS = 1
    DRAFT_STATUS = 2
    STATUS_CHOICES = (
        (LIVE_STATUS, 'Live'),
        (DRAFT_STATUS, 'Draft'),
    )
    title = models.CharField(max_length=200)
    slug = models.SlugField(help_text='Populates from title field.')
    date_completed = models.DateField(null=True, blank=True)
    vison_description = models.TextField(help_text='Please use Markdown syntax. No HTML is allowed.')
    work_description = models.TextField(help_text='Please use Markdown syntax. No HTML is allowed.')
    category = models.ManyToManyField(Category)
    lead_photo = models.ImageField(upload_to='projects/photos', help_text='Will also be used as thumbnail for category listing.')
    gallery = models.ForeignKey(Gallery)
    status = models.IntegerField(choices=STATUS_CHOICES, default=2, help_text="Only projects with a status of 'live' will be displayed publicly.")

    objects = models.Manager()
    live = LiveProjectManager()

class Category(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(help_text='Populates from title field.')
    description = models.TextField(help_text='Please use Markdown syntax. No HTML is allowed.', blank=True)

    class Meta:
        verbose_name_plural = 'Categories'
        ordering = ('title',)

    def __str__(self):
        return self.slug

    @models.permalink
    def get_absolute_url(self):
        return ('categories:detail',
                (), 
                {'slug': self.slug})

查看:

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>

0 个答案:

没有答案