Mercurial > public > madeira
diff gigs/views.py @ 71:e2868ad47a1e
For Django 1.4, using the new manage.py.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 14 Apr 2012 16:40:29 -0500 |
parents | madeira/gigs/views.py@5ff9c130f47f |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/gigs/views.py Sat Apr 14 16:40:29 2012 -0500 @@ -0,0 +1,76 @@ +""" +Views for the gigs application. + +""" +import collections +import datetime + +from django.db import connection +from django.shortcuts import render + +from gigs.models import Band, Gig + + +def gigs(request): + """ + This view function renders the main gigs view, showing upcoming and past + gigs as well as some statistics. + + """ + today = datetime.date.today() + gigs = Gig.objects.select_related('venue', 'flyer', 'venue__city', + 'venue__city__state', 'venue__city__country') + upcoming = [] + previous = [] + + # To avoid many, many database hits in the template, we get all the + # bands out at once. We also get the many-to-many intermediate table + # that Django generated for us so we can associate bands to gigs. + # Since we don't know about this table we drop into raw SQL to get + # the contents. + + bands = dict((band.id, band) for band in Band.objects.all()) + cursor = connection.cursor() + cursor.execute('SELECT * FROM gigs_gig_bands') + gig_bands = collections.defaultdict(list) + for row in cursor.fetchall(): + gig_bands[row[1]].append(bands[row[2]]) + + for gig in gigs: + gig.bands_ = gig_bands[gig.id] + if gig.date >= today: + upcoming.append(gig) + else: + previous.append(gig) + + upcoming.reverse() + + stats = {} + venues = set() + cities = set() + states = set() + countries = set() + for gig in previous: + venues.add(gig.venue.id) + cities.add(gig.venue.city.id) + if gig.venue.city.state: + states.add(gig.venue.city.state.id) + if gig.venue.city.country: + countries.add(gig.venue.city.country.id) + + stats['count'] = len(previous) + stats['venues'] = len(venues) + stats['cities'] = len(cities) + stats['states'] = len(states) + stats['countries'] = len(countries) + stats['bands'] = len(bands) + + flyer_gigs = Gig.objects.exclude(flyer__isnull = True).select_related( + 'venue', 'flyer').order_by('-date') + + return render(request, 'gigs/gigs.html', { + 'upcoming' : upcoming, + 'previous' : previous, + 'stats' : stats, + 'flyer_gigs' : flyer_gigs, + })