Putting the following code somewhere after settings.py is imported (a
new app called 'startup' in __init__.py, with 'startup' added first in
INSTALLED_APPS is a good place), will allow you to lock models to
databases via a manager's forced_using attribute. This definitely not
'the best way', as monkey patching is a little nasty. However, I'm not
sure this would be accepted as a patch (when formulated as such), and
this works for me, so i'm just sharing it for whoever needs it.

I haven't seen any bugs, so if you use it and find any let me know.

Thanks again to Alex for making the multidb branch.

-CB

------------------------------------

from django.db import models

def hijack_for_partitioning():
    """This class enables you to add a forced_using = 'db_name' to a
manager,
    which will lock queries and saves for that model to that
particular db.

    In addition, if this is /not/ specified on a custom manager, it
will lock every model to the 'default' db.
    """
    _real_save = models.Model.save
    def save(self, *args, **kwargs):
        kwargs['using'] = type(self).objects.forced_using #Makes sure
instances are saved in the proper place
        _real_save(self, *args, **kwargs)
    models.Model.save = save

    _real_get_query_set = models.Manager.get_query_set
    def get_query_set(self):
        qs = _real_get_query_set(self)
        if hasattr(self, 'forced_using'):
            qs = qs.using(self.forced_using)
            qs._real_using = qs.using
            qs.using = lambda new_using: qs._real_using(qs._db)
#Disable changing db with .using() - required because related manager
tries to set .using after we return the qs
        return qs
    models.Manager.get_query_set = get_query_set

    models.Manager.forced_using = 'default'
    models.Manager.use_for_related_fields = True

hijack_for_partitioning()

--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.


Reply via email to