[英]Override get_queryset method in listview for nested cycles
im trying to render 3 rankings in the same templates. 即时通讯试图在相同的模板中呈现3个排名。 I mean, i have three cities and each city has too many photos (the three first photo that has most votes, but this is other issue).
我的意思是,我有三个城市,每个城市的照片太多(前三张照片得票最多,但这是另一个问题)。
My models: 我的模特:
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"
Here is my view. 这是我的看法。 I know that i need override get_queryset, im trying but i cant get put it works:
我知道我需要覆盖get_queryset,即时通讯正在尝试,但我无法投入使用:
class RankingPhotosView(ListView):
model = Photo
template_name = 'ranking.html'
In other words, i need render in my template, something like: 换句话说,我需要在模板中进行渲染,例如:
Bogotá:
Foto1
Foto2
Foto3
New York:
Foto4
Foto5
Foto6
London:
Foto7
Foto8
Foto9
Something like: 就像是:
Photo.objects.filter(school__city__id=some_id_here)
Will give you as result the photos for a given city. 结果将为您提供给定城市的照片。
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
Now in your template: 现在在您的模板中:
{% for key, value in results %}
{{ key }}
{% for photo in value %}
- {{ photo }}
{% endfor %}
{% endfor %}
I have not tested this code so it could not work in one go (specially the template part), but it should help you getting started. 我尚未测试此代码,因此无法一劳永逸地工作(特别是模板部分),但它应该可以帮助您入门。 If you find issues with it, leave a comment so i can edit the answer.
如果您发现问题,请发表评论,以便我编辑答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.