Thursday, September 4. 2008

First of all, if you don't already know django and CouchDB, take a look at their websites. You might ask "Why? Why this combination?". Both django as an application framework and CouchDB as a database engine are state of the art technologies. So, why not? While searching the net, numerous forums and websites propagate their user's silent wish to incorporate a CouchDB backend into django: 123
Let's take a closer look. django's backend engines are all SQL based and suitable for relational data organisation - oracle, mysql, postgres, sqlite. That means tables can be created according to a data description and have relationships, e.g. a group contains many users and a user can be in many groups; both users and groups have predefined attributes such as a name. CouchDB on the other hand is document based and schemafree. Each document can be structured differently. You just throw whichever data you have serialised as JSON object into the database. That's it. A document could be an address or details of a book in your personal library or any other data representable as JSON. As a bonus, each document may have any number of file attachments.
Now, in order to use django and CouchDB hand in hand there are two major strategies, both with it's catches:
One. Develop a proper and seamlessly integrating django model backend using CouchDB. Since most database queries in django use either django's query class django.db.models.sql.query.Query or plain SQL, a new django model must either be able to parse SQL or implement all functions of this query class. (You could also re-implement each save() function of all uses of a django model for starters, but that would be the opposite of an abstracted model component.)
Two. Completely ignore the existence of a model abstraction and implement data storage directly into django views -- who needs MVC anyway. PHP versions 1-3 have taught us to implement everything inside a single view anyway A nice example can be found here.
While you may already have thoughts about how easy it is to implement a SQL parser, map a relational model upon a document based model and stick it all together into a django model backend (which - by the way - is quite possible), I found that django rather emphasises the "rapid" in rapid development. So, we'll linger with option number two for the moment. Let's see, what we can use of the django world now:
- urlpatterns
- templates
- views
- the file upload handler
- sessions (with SESSION_ENGINE = 'django.contrib.sessions.backends.cache')
- caching (CACHE_BACKEND = 'locmem://')
- the authentication backend (hm?)

In order to use the authentication backend without a django model backend, sessions and caching must already be configured as above, django.contrib.sites must be disabled, and a custom auth backend must be implemented as documented. Then, it is advisable to prevent anyone from calling save() or get_and_delete_messages() on a User object: