Skip to content

Instantly share code, notes, and snippets.

@jeroenp
Created February 9, 2012 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenp/1781101 to your computer and use it in GitHub Desktop.
Save jeroenp/1781101 to your computer and use it in GitHub Desktop.
Database switching support in FeinCMS
--- ../milieubarometer/lib/python2.6/site-packages/feincms/models.py 2011-11-30 17:16:41.000000000 +0100
+++ lib/python2.6/site-packages/feincms/models.py 2012-02-09 17:59:55.000000000 +0100
@@ -104,6 +104,7 @@
def __init__(self, item):
item._needs_content_types()
self.item = item
+ self.using = 'default'
self._cache = {
'cts': {},
}
@@ -160,7 +161,7 @@
return self._cache['counts']
def _fetch_content_type_count_helper(self, pk, regions=None):
- tmpl = ['SELECT %d AS ct_idx, region, COUNT(id) FROM %s WHERE parent_id=%s']
+ tmpl = ['SELECT %d AS ct_idx, region, COUNT(id) FROM `%s`.`%s` WHERE parent_id=%s']
args = []
if regions:
@@ -170,7 +171,19 @@
tmpl.append('GROUP BY region')
tmpl = u' '.join(tmpl)
- sql = ' UNION '.join([tmpl % (idx, cls._meta.db_table, pk)\
+ db_name = 'default'
+ for rel in self.item._meta.get_all_related_objects():
+ if rel.model in self.item._feincms_content_types:
+ manager = getattr(self.item, rel.get_accessor_name())
+ db_name = manager.all().db
+ # Assuming that related's are all in the same database:
+ break
+
+ from django.conf import settings
+ sql_db_name = settings.DATABASES[db_name]['NAME']
+ self.using = db_name
+
+ sql = ' UNION '.join([tmpl % (idx, sql_db_name, cls._meta.db_table, pk)\
for idx, cls in enumerate(self.item._feincms_content_types)])
sql = 'SELECT * FROM ( ' + sql + ' ) AS ct ORDER BY ct_idx'
@@ -202,7 +215,7 @@
if type not in self._cache['cts']:
if counts:
self._cache['cts'][type] = list(type.get_queryset(
- reduce(operator.or_, (Q(region=r[0], parent=r[1]) for r in counts))))
+ reduce(operator.or_, (Q(region=r[0], parent=r[1]) for r in counts)), using=self.using))
else:
self._cache['cts'][type] = []
@@ -532,8 +545,8 @@
self.id,
)
- def get_queryset(cls, filter_args):
- return cls.objects.select_related().filter(filter_args)
+ def get_queryset(cls, filter_args, using='default'):
+ return cls.objects.using(using).select_related().filter(filter_args)
attrs = {
'__module__': cls.__module__, # The basic content type is put into
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment