bgneal@44: """ bgneal@44: Views for the gigs application. bgneal@44: bgneal@44: """ bgneal@44: import collections bgneal@44: import datetime bgneal@44: bgneal@44: from django.db import connection bgneal@44: from django.shortcuts import render bgneal@44: bgneal@44: from gigs.models import Band, Gig bgneal@44: bgneal@44: bgneal@44: def gigs(request): bgneal@44: """ bgneal@44: This view function renders the main gigs view, showing upcoming and past bgneal@44: gigs as well as some statistics. bgneal@44: bgneal@44: """ bgneal@44: today = datetime.date.today() bgneal@44: gigs = Gig.objects.select_related('venue', 'flyer', 'venue__city', bgneal@44: 'venue__city__state', 'venue__city__country') bgneal@44: upcoming = [] bgneal@44: previous = [] bgneal@44: bgneal@44: # To avoid many, many database hits in the template, we get all the bgneal@44: # bands out at once. We also get the many-to-many intermediate table bgneal@44: # that Django generated for us so we can associate bands to gigs. bgneal@44: # Since we don't know about this table we drop into raw SQL to get bgneal@44: # the contents. bgneal@44: bgneal@44: bands = dict((band.id, band) for band in Band.objects.all()) bgneal@44: cursor = connection.cursor() bgneal@57: cursor.execute('SELECT * FROM gigs_gig_bands') bgneal@44: gig_bands = collections.defaultdict(list) bgneal@44: for row in cursor.fetchall(): bgneal@44: gig_bands[row[1]].append(bands[row[2]]) bgneal@44: bgneal@44: for gig in gigs: bgneal@44: gig.bands_ = gig_bands[gig.id] bgneal@44: if gig.date >= today: bgneal@44: upcoming.append(gig) bgneal@44: else: bgneal@44: previous.append(gig) bgneal@44: bgneal@44: upcoming.reverse() bgneal@44: bgneal@44: stats = {} bgneal@44: venues = set() bgneal@44: cities = set() bgneal@44: states = set() bgneal@44: countries = set() bgneal@44: for gig in previous: bgneal@44: venues.add(gig.venue.id) bgneal@44: cities.add(gig.venue.city.id) bgneal@44: if gig.venue.city.state: bgneal@44: states.add(gig.venue.city.state.id) bgneal@44: if gig.venue.city.country: bgneal@44: countries.add(gig.venue.city.country.id) bgneal@44: bgneal@44: stats['count'] = len(previous) bgneal@44: stats['venues'] = len(venues) bgneal@44: stats['cities'] = len(cities) bgneal@44: stats['states'] = len(states) bgneal@44: stats['countries'] = len(countries) bgneal@44: stats['bands'] = len(bands) bgneal@44: bgneal@44: flyer_gigs = Gig.objects.exclude(flyer__isnull = True).select_related( bgneal@44: 'venue', 'flyer').order_by('-date') bgneal@44: bgneal@44: return render(request, 'gigs/gigs.html', { bgneal@44: 'upcoming' : upcoming, bgneal@44: 'previous' : previous, bgneal@44: 'stats' : stats, bgneal@44: 'flyer_gigs' : flyer_gigs, bgneal@44: })