在listview中覆盖嵌套循环的get_queryset方法

时间:2015-02-04 19:28:49

标签: python django listview

我试图在同一个模板中渲染3个排名。我的意思是,我有三个城市,每个城市都有太多的照片(三张第一张照片票数最多,但这是另一个问题)。

我的模特:

class City(models.Model):
    city = models.CharField(max_length=100)

    def __unicode__(self):
        return self.city

    class Meta():
        verbose_name_plural = "Cities"

class School(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City)


    def __unicode__(self):
        return self.name

    class Meta():
        verbose_name_plural = "Schools"

class Album(models.Model):
    name = models.CharField(max_length=100)
    school = models.ForeignKey(School)

    def __unicode__(self):
        return str(self.name)

    class Meta():
        verbose_name_plural = "Albums"

class Photo(models.Model):
    school = models.ForeignKey(School)
    photo = models.ImageField(upload_to='fotos')
    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return str(self.photo)

    class Meta():
        verbose_name_plural = "Photos"

这是我的看法。我知道我需要覆盖get_queryset,即时尝试,但我不能让它工作:

class RankingPhotosView(ListView):
    model = Photo
    template_name = 'ranking.html'

换句话说,我需要在我的模板中渲染,例如:

Bogotá:
Foto1
Foto2
Foto3

New York:
Foto4
Foto5
Foto6

London:
Foto7
Foto8
Foto9

1 个答案:

答案 0 :(得分:0)

类似的东西:

Photo.objects.filter(school__city__id=some_id_here)

将为您提供给定城市的照片。

class RankingPhotosView(TemplateView):
    template_name = 'ranking.html'

    def get_context_data(self, **kwargs):
        context = super(RankingPhotosView, self).get_context_data(**kwargs)
        temp = {}
        for city in City.objects.all():
            temp[city.name] = Photo.objects.filter(school__city__id=city.id)
        context['results'] = temp

现在在你的模板中:

{% for key, value in results %}
    {{ key }}
    {% for photo in value %}
        - {{ photo }}
    {% endfor %}
{% endfor %}

我没有测试过这段代码所以它不能一次性工作(特别是模板部分),但它应该可以帮助你入门。如果您发现问题,请发表评论,以便我可以编辑答案。