Maintain a cached count of Child instances

This commit is contained in:
Christopher C. Wells 2020-01-28 21:49:10 -08:00 committed by Christopher Charbonneau Wells
parent e93c70bf2c
commit fd6bcfe9a5
1 changed files with 13 additions and 0 deletions

View File

@ -2,6 +2,7 @@
from datetime import timedelta from datetime import timedelta
from django.conf import settings from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
@ -93,6 +94,8 @@ class Child(models.Model):
objects = models.Manager() objects = models.Manager()
cache_key_count = 'core.child.count'
class Meta: class Meta:
default_permissions = ('view', 'add', 'change', 'delete') default_permissions = ('view', 'add', 'change', 'delete')
ordering = ['last_name', 'first_name'] ordering = ['last_name', 'first_name']
@ -105,6 +108,11 @@ class Child(models.Model):
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
self.slug = slugify(self) self.slug = slugify(self)
super(Child, self).save(*args, **kwargs) super(Child, self).save(*args, **kwargs)
cache.set(self.cache_key_count, Child.objects.count(), None)
def delete(self, using=None, keep_parents=False):
super(Child, self).delete(using, keep_parents)
cache.set(self.cache_key_count, Child.objects.count(), None)
def name(self, reverse=False): def name(self, reverse=False):
if reverse: if reverse:
@ -112,6 +120,11 @@ class Child(models.Model):
return '{} {}'.format(self.first_name, self.last_name) return '{} {}'.format(self.first_name, self.last_name)
@classmethod
def count(cls):
""" Get a (cached) count of total number of Child instances. """
return cache.get_or_set(cls.cache_key_count, Child.objects.count, None)
class DiaperChange(models.Model): class DiaperChange(models.Model):
model_name = 'diaperchange' model_name = 'diaperchange'