comparison 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
comparison
equal deleted inserted replaced
70:f26cdda0ad8b 71:e2868ad47a1e
1 """
2 Views for the gigs application.
3
4 """
5 import collections
6 import datetime
7
8 from django.db import connection
9 from django.shortcuts import render
10
11 from gigs.models import Band, Gig
12
13
14 def gigs(request):
15 """
16 This view function renders the main gigs view, showing upcoming and past
17 gigs as well as some statistics.
18
19 """
20 today = datetime.date.today()
21 gigs = Gig.objects.select_related('venue', 'flyer', 'venue__city',
22 'venue__city__state', 'venue__city__country')
23 upcoming = []
24 previous = []
25
26 # To avoid many, many database hits in the template, we get all the
27 # bands out at once. We also get the many-to-many intermediate table
28 # that Django generated for us so we can associate bands to gigs.
29 # Since we don't know about this table we drop into raw SQL to get
30 # the contents.
31
32 bands = dict((band.id, band) for band in Band.objects.all())
33 cursor = connection.cursor()
34 cursor.execute('SELECT * FROM gigs_gig_bands')
35 gig_bands = collections.defaultdict(list)
36 for row in cursor.fetchall():
37 gig_bands[row[1]].append(bands[row[2]])
38
39 for gig in gigs:
40 gig.bands_ = gig_bands[gig.id]
41 if gig.date >= today:
42 upcoming.append(gig)
43 else:
44 previous.append(gig)
45
46 upcoming.reverse()
47
48 stats = {}
49 venues = set()
50 cities = set()
51 states = set()
52 countries = set()
53 for gig in previous:
54 venues.add(gig.venue.id)
55 cities.add(gig.venue.city.id)
56 if gig.venue.city.state:
57 states.add(gig.venue.city.state.id)
58 if gig.venue.city.country:
59 countries.add(gig.venue.city.country.id)
60
61 stats['count'] = len(previous)
62 stats['venues'] = len(venues)
63 stats['cities'] = len(cities)
64 stats['states'] = len(states)
65 stats['countries'] = len(countries)
66 stats['bands'] = len(bands)
67
68 flyer_gigs = Gig.objects.exclude(flyer__isnull = True).select_related(
69 'venue', 'flyer').order_by('-date')
70
71 return render(request, 'gigs/gigs.html', {
72 'upcoming' : upcoming,
73 'previous' : previous,
74 'stats' : stats,
75 'flyer_gigs' : flyer_gigs,
76 })