Skip to content

Instantly share code, notes, and snippets.

@higs4281
Last active August 29, 2015 14:03
Show Gist options
  • Save higs4281/a0ed61961a554a2b7642 to your computer and use it in GitHub Desktop.
Save higs4281/a0ed61961a554a2b7642 to your computer and use it in GitHub Desktop.
django queries
"""
python data structures:
https://docs.python.org/2/tutorial/datastructures.html
reference pages
https://docs.djangoproject.com/en/1.5/
query filters
https://docs.djangoproject.com/en/1.5/ref/models/querysets/#methods-that-return-new-querysets
field lookups
https://docs.djangoproject.com/en/1.5/topics/db/queries/#field-lookups
LIST: python's collector workhorse (an 'array' in javascript)
number_list = [1, 2, 3, 4, 5]
slicing:
number_list[0]
number_list[3]
number_list[1:2]
number_list[-1]
adding:
number_list.append(6)
counting:
len(number_list)
DICTIONARY: the heart of objects and models: key-value pairs (an 'object' in javascript)
person = {'first_name': 'John', 'last_name': 'Martin'}
getting values:
person['first_name'] returns 'John'
seeing the keys:
person.keys() returns ['first_name', 'last_name']
3 basic commands:
dir() -- this returns local variables, or the variables of an object named in the parens
len() -- this counts whatever is inside the parens
for ... -- starts a loop that cycles through a collection of objects. example:
for person in person_query:
print person.name
"""
# to fire up a python session inside a django project:
python manage.py shell
# imports on the arrest-watcher server
from arrestee.models import Arrestee
from watchlist.models import Person
from crime_places.models import Place
# imports on the crime-watcher server
from crime.models import Incident, Agency
from places.models import Place, City, State, County, ZipCode
# helper function
def print_vals(obj):
keylist = sorted([key for key in obj._meta.get_all_field_names()], key=lambda s: s.lower())
try:
print "%s model values for %s:\n" % (obj._meta.object_name, obj)
except:
pass
for key in keylist:
try:
print "%s: %s" % (key, obj.__getattribute__(key))
except:
pass
header = [
'first_name',
'middle_name',
'last_name',
'name_suffix',
'birth_date',
'arrest_agency',
'arrest_date',
'arrest_location',
'arrest_location_description',
'gender',
'race',
'home_address',
'home_city',
'home_state',
'home_zip',
'transient',
'employer',
'occupation'
]
from csvkit import CSVKitWriter as ckw
x2 = Arrestee.objects.filter(
booking_county__name='Hillsborough',
charge__description__contains='WRITTEN PROMISE').order_by('-arrest_date').distinct()
with open('written_promise.csv', 'w') as f:
writer = ckw(f)
writer.writerow(header)
for each in x2:
writer.writerow([each.__getattribute__(key) for key in header])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment