Skip to content

Commit

Permalink
Export community areas with the most DUIs
Browse files Browse the repository at this point in the history
Add queries and a management command
  • Loading branch information
ghing committed Dec 10, 2014
1 parent 0cef7f7 commit a2cbe77
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,13 @@ Export table of drug convictions

./manage.py export_drug_stats drug_by_class > export/drug_by_class.csv

Export table of top community areas by DUI
------------------------------------------

::

./manage.py export_dui_convictions_by_geo --model CommunityArea --count 20 > export/top_dui_community_areas.csv


Manual Processes
================
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import csv
from optparse import make_option

from django.core.management.base import BaseCommand

import convictions_data.models

class Command(BaseCommand):
help = ("Export CSV table showing most common conviction statute by geography")
option_list = BaseCommand.option_list + (
make_option('--count',
action='store',
type='int',
default=20,
dest='count',
help="Show this many statutes"),
make_option('--model',
action='store',
default='CommunityArea',
dest='model',
help="Get most common statutes for this model"),
)

def handle(self, *args, **options):
model_cls = getattr(convictions_data.models, options['model'])
qs = model_cls.objects.all().with_dui_annotations().order_by('-num_dui')

fieldnames = ['name', 'count', 'pct']
writer = csv.DictWriter(self.stdout,
fieldnames=fieldnames)

writer.writeheader()

for geo in qs[:options['count']]:
row = {
'name': geo.name,
'count': geo.num_dui,
'pct': geo.pct_dui,
}
writer.writerow(row)
41 changes: 40 additions & 1 deletion convictions_data/query/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ def with_conviction_annotations(self):
"AND {conviction_table}.iucr_category = 'Homicide'"
).format(conviction_table=conviction_table,
matches_this_id=matches_this_id_where_sql)
# BOOKMARK

codes = ["'{}'".format(c) for c in crimes_affecting_women_iucr_codes]
affecting_women_iucr_codes_str = ", ".join(codes)
num_affecting_women_sql = ('SELECT COUNT({conviction_table}.id) '
Expand Down Expand Up @@ -636,6 +636,45 @@ def with_conviction_annotations(self):

return annotated_qs

def with_dui_annotations(self):
this_table = self.model._meta.db_table
conviction_table = self.model.get_conviction_model()._meta.db_table
conviction_related_col = self.model.get_conviction_related_column_name()
matches_this_id_where_sql = ('{conviction_table}.{related_col} = '
'{this_table}.id').format(conviction_table=conviction_table,
this_table=this_table, related_col=conviction_related_col)
num_dui_sql = ('SELECT COUNT({conviction_table}.id) '
'FROM {conviction_table} '
'WHERE {matches_this_id} '
'AND {conviction_table}.final_statute_formatted ILIKE \'625-5/11-501%%\''
).format(conviction_table=conviction_table,
matches_this_id=matches_this_id_where_sql)
pct_dui_sql = ('SELECT CAST((SELECT COUNT({conviction_table}.id) '
'FROM {conviction_table} '
'WHERE {matches_this_id} '
'AND {conviction_table}.final_statute_formatted ILIKE '
'\'625-5/11-501%%\') AS FLOAT) / '
'(SELECT COUNT({conviction_table}.id) '
'FROM {conviction_table} '
'WHERE {matches_this_id}) '
).format(conviction_table=conviction_table,
matches_this_id=matches_this_id_where_sql)
dui_per_capita_sql = ('SELECT CAST(COUNT({conviction_table}.id) AS FLOAT) / '
'"{this_table}"."total_population" '
'FROM {conviction_table} '
'WHERE {matches_this_id} '
'AND {conviction_table}.final_statute_formatted ILIKE '
'\'625-5/11-501%%\''
).format(conviction_table=conviction_table,
this_table=this_table,
matches_this_id=matches_this_id_where_sql)

return self.extra(select={
'num_dui': num_dui_sql,
'pct_dui': pct_dui_sql,
'dui_per_capita': dui_per_capita_sql,
})

def geojson(self, simplify=0.0):
"""
Serialize models in this QuerySet as a GeoJSON FeatureCollection.
Expand Down

0 comments on commit a2cbe77

Please sign in to comment.