Django: Querying data from the Python shell

I needed to get some stats for some research that we’re doing and was happy to see that you can use Django and the python shell to query testament data in a way that’s database independent.  It’s a little unintuitive if you’re thinking in SQL mode, but it is usable and super-helpful.  I wanted to share it with ya’ll in case you needed to quickly pull stats or examine info.

Helpful reference Django docs:

  • http://docs.djangoproject.com/en/dev/topics/db/queries/#making-queries
  • http://docs.djangoproject.com/en/dev/ref/models/querysets/#queryset-api-reference

Print the prison name, city, and state of all prisons that received a package sent by the Midwest Pages to Prisones Project from 2009-01-01 to 2009-03-22

geoff@btp:/var/www/testament/testament_trunk/btp$ python manage.py shell
>>> import datetime
>>> from core.models import Prison, Package
>>> start_date = datetime.date(2009, 1, 1)
>>> end_date = datetime.date(2009, 3, 22)
>>> prisons = Prison.objects.filter(package__sent_on__range=(start_date, end_date), package__group__username__exact='mwpp').distinct()
>>> for prison in prisons:
>>>    print "%s %s, %s" % (prison.name, prison.city, prison.state)