简体   繁体   中英

Override get_queryset method in listview for nested cycles

im trying to render 3 rankings in the same templates. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM