Multiple Database Config In Django 1.2
Solution 1:
Yeah, it is a little bit complicated.
There are a number of ways you could implement it. Basically, you need some way of indicating which models are associated with which database.
First option
Here's the code that I use; hope it helps.
from django.db import connections
classDBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""defdb_for_read(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
passreturnNonedefdb_for_write(self, model, **hints):
m = model.__module__.split('.')
try:
d = m[-1]
if d in connections:
return d
except IndexError:
passreturnNonedefallow_syncdb(self, db, model):
"Make sure syncdb doesn't run on anything but default"if model._meta.app_label == 'myapp':
returnFalseelif db == 'default':
returnTruereturnNone
The way this works is I create a file with the name of the database to use that holds my models. In your case, you'd create a separate models
-style file called asterisk.py
that was in the same folder as the models for your app.
In your models.py
file, you'd add
from asterisk import *
Then when you actually request a record from that model, it works something like this:
records = MyModel.object.all()
- module for
MyModel
ismyapp.asterisk
- there's a connection called "asterisk" so use it instead of "default"
Second Option
If you want to have per-model control of database choice, something like this would work:
from django.db import connections
classDBRouter(object):
"""A router to control all database operations on models in
the contrib.auth application"""defdb_for_read(self, model, **hints):
ifhasattr(model,'connection_name'):
return model.connection_name
returnNonedefdb_for_write(self, model, **hints):
ifhasattr(model,'connection_name'):
return model.connection_name
returnNonedefallow_syncdb(self, db, model):
ifhasattr(model,'connection_name'):
return model.connection_name
returnNone
Then for each model:
classMyModel(models.Model):
connection_name="asterisk"#etc...
Note that I have not tested this second option.
Solution 2:
An addendum to Jordans answer above. For the second option, the allow_syncdb method works correctly as follows:
defallow_syncdb(self, db, model):
ifhasattr(model,'connection_name'):
return model.connection_name == db
return db == 'default'
Solution 3:
Does the documentation on automatic database routing and manually selecting a database not help?
Post a Comment for "Multiple Database Config In Django 1.2"