Jan Mészáros reflections on technology and society

21Oct/092

Django multiple database support with DB switch feature

Our Django installation is capable to connect to as many databases as desired and switch between databases in according to session data. We reached this feature overriding several internal Django classes, according to recommendations on http://groups.google.com/group/django-users/msg/d1d7e0af565cc444?. All multiple database features are done without changes in original Django code.

Partial how-to can be found on http://kfalck.net/2009/07/01/multiple-databases-and-sharding-with-django too.

The solution is successfully tested for more than one month in real-world application and this application is going to be used into production environment soon.

For implementation details or questions leave a comment below.

Comments (2) Trackbacks (0)
  1. Are you able to access Foreign Key in a table which points to some other table which is present in some other database.

  2. Yes, I am able to do that. The first condition is not to use foreign key constraints in the first table with foreign key on database level. This is apparent for MySQL MyISAM engine. If you use any other engine or any other DB backend, Django will implicitly try to create foreign key constraint. In that case, it is better to create the table manually with the foreign key column of simple integer type without any constraints. The other table, living in another database, must be defined as regular django model, which inherits from your custom overriden “django.db.models.Model” class. The overriden class must be using a custom “Manager”, which i simply overriden “django.db.models.Manager” class.
    If you want to perform SELECT or UPDATE commands on another database tables, you have to override the “get_query_set” method in your custom manager. If you also want do perform INSERT commands, you have to override the “_insert” method too.
    For detailed how-to, please follow this link: http://djangrrl.com/view/multiple-database-connection-a-simple-use-case/


Leave a comment


No trackbacks yet.