"djpeewee": use the peewee ORM with your Django models

I sat down and started working on a new library shortly after posting about
Django's missing API for generating SQL.
djpeewee
is the result, and provides a simple translate() function that will recursively
translate a Django model graph into a set of "peewee equivalents". The peewee
versions can then be used to construct queries which can be passed back into
Django as a "raw query".

Here are a couple scenarios when this might be useful:

Joining on fields that are not related by foreign key (for example UUID fields).

With Django I believe you would have to use the extra() method. Edit: a helpful redditor pointed out this is not the case and you can use F() objects to write .filter(end__gt=F('start') + two_hours). At any rate, here is the equivalent with peewee:

So P is a container for all the auto-generated models, and query is a peewee
SelectQuery object. By passing the query's SQL and parameters into django's raw()
method, we can run this query and retrieve instances of our Django model:

Admittedly this is kind of a strange workflow. I will have to find a way to try
it out in my work before I decide if I like it -- all those "interesting" queries
I was working on last week would be good candidates! What do you think? Good
idea, gross hack, or somewhere in between?

A more complicated example

Things get a bit more interesting when you bring foreign keys into the mix. The
translate() function will automatically traverse explicit foreign keys and
many-to-many relationships. Let's suppose we're working with the following models
in our app:

If we attempt to traverse Person, though, we will only get that table because
it has no 1-to-many relationships. By specifying backrefs=True we can force
the translate() function to follow external foreign keys:

Thanks for your comment, Josh! I agree that the true fix should belong in Django, and a "wrapper" around extra() seems like a pretty flexible option. This PR adds arithmetic to aggregates and looks pretty nice, hopefully that will get merged.