Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Last active December 15, 2015 05:39
Show Gist options
  • Save hirokazumiyaji/5211077 to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/5211077 to your computer and use it in GitHub Desktop.
# coding: utf-8
import random
from django.conf import settings
from django.db import models
from library.cachemethod.decorator import cachemethod
from library.cachemethod.api import delete_method_cache
class MasterModelQuerySet(models.query.QuerySet):
@property
def db(self):
if self._for_write:
return self._db or router.db_for_write(self.model)
if hasattr(settings, 'SLAVE_DATABASES') and isinstance(settings.SLAVE_DATABASES, list):
return random.choice(settings.SLAVE_DATABASES)
return self._db or router.db_for_read(self.model)
class MasterModelManager(models.Manager):
def get_query_set(self):
return MasterModelQuerySet(self.model)
class MasterModel(models.Model):
objects = MasterModelManager()
class Meta:
abstract = True
@classmethod
@cachemethod
def get(cls, pk):
try:
return cls.objects.get(pk=pk)
except:
return None
@classmthod
@cachemethod
def get_all(cls):
return list(cls.objects.all())
def _delete_cache(self):
delete_method_cache()
def save(self, *args, **kwargs):
super(self.__class__, self).save(*args, **kwargs)
self.delete_cache()
def delete(self, *args, **kwargs):
super(self.__class__, self).delete(*args, **kwargs)
self.delete_cache()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment