3 from urllib import quote_plus, urlencode
4 from django.db import models, IntegrityError, connection, transaction
5 from django.utils.http import urlquote as django_urlquote
6 from django.utils.html import strip_tags
7 from django.core.urlresolvers import reverse
8 from django.contrib.contenttypes import generic
9 from django.contrib.contenttypes.models import ContentType
10 from django.core.cache import cache
11 from django.template.defaultfilters import slugify
12 from django.db.models.signals import post_delete, post_save, pre_save, pre_delete
13 from django.utils.translation import ugettext as _
14 from django.utils.safestring import mark_safe
15 from django.contrib.sitemaps import ping_google
16 import django.dispatch
17 from forum import settings
21 class LazyQueryList(object):
22 def __init__(self, model, items):
26 def __getitem__(self, k):
27 return self.model.objects.get(id=self.items[k])
31 yield self.model.objects.get(id=id)
34 return len(self.items)
36 class CachedQuerySet(models.query.QuerySet):
38 if len(self.query.extra) == 0:
39 return LazyQueryList(self.model, list(self.values_list('id', flat=True)))
43 def obj_from_datadict(self, datadict):
45 obj.__dict__.update(datadict)
48 def get(self, *args, **kwargs):
50 pk = [v for (k,v) in kwargs.items() if k in ('pk', 'pk__exact', 'id', 'id__exact'
51 ) or k.endswith('_ptr__pk') or k.endswith('_ptr__id')][0]
56 key = self.model.cache_key(pk)
60 obj = super(CachedQuerySet, self).get(*args, **kwargs)
63 obj = self.obj_from_datadict(obj)
64 obj.reset_original_state()
68 return super(CachedQuerySet, self).get(*args, **kwargs)
70 class CachedManager(models.Manager):
71 use_for_related_fields = True
73 def get_query_set(self):
74 return CachedQuerySet(self.model)
76 def get_or_create(self, *args, **kwargs):
78 return self.get(*args, **kwargs)
80 return super(CachedManager, self).get_or_create(*args, **kwargs)
83 class DenormalizedField(object):
84 def __init__(self, manager, *args, **kwargs):
85 self.manager = manager
86 self.filter = (args, kwargs)
88 def setup_class(self, cls, name):
89 dict_name = '_%s_dencache_' % name
92 val = inst.__dict__.get(dict_name, None)
95 val = getattr(inst, self.manager).filter(*self.filter[0], **self.filter[1]).count()
96 inst.__dict__[dict_name] = val
101 def reset_cache(inst):
102 inst.__dict__.pop(dict_name, None)
105 cls.add_to_class(name, property(getter))
106 cls.add_to_class("reset_%s_cache" % name, reset_cache)
109 class BaseMetaClass(models.Model.__metaclass__):
112 def __new__(cls, *args, **kwargs):
113 new_cls = super(BaseMetaClass, cls).__new__(cls, *args, **kwargs)
115 BaseMetaClass.to_denormalize.extend(
116 [(new_cls, name, field) for name, field in new_cls.__dict__.items() if isinstance(field, DenormalizedField)]
122 def setup_denormalizes(cls):
123 for new_cls, name, field in BaseMetaClass.to_denormalize:
124 field.setup_class(new_cls, name)
127 class BaseModel(models.Model):
128 __metaclass__ = BaseMetaClass
130 objects = CachedManager()
136 def __init__(self, *args, **kwargs):
137 super(BaseModel, self).__init__(*args, **kwargs)
138 self.reset_original_state(kwargs.keys())
141 def cache_key(cls, pk):
142 return '%s:%s:%s' % (settings.APP_URL, cls.__name__, pk)
144 def reset_original_state(self, reset_fields=None):
145 self._original_state = self._as_dict()
148 self._original_state.update(dict([(f, None) for f in reset_fields]))
150 def get_dirty_fields(self):
151 return [f.name for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]]
154 return dict([(name, getattr(self, name)) for name in
155 ([f.attname for f in self._meta.fields] + [k for k in self.__dict__.keys() if k.endswith('_dencache_')])
158 def _get_update_kwargs(self):
160 (f.name, getattr(self, f.name)) for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]
163 def save(self, *args, **kwargs):
164 put_back = [k for k, v in self.__dict__.items() if isinstance(v, models.expressions.ExpressionNode)]
167 self.__class__.objects.filter(id=self.id).update(**self._get_update_kwargs())
169 super(BaseModel, self).save()
173 self.__dict__.update(
174 self.__class__.objects.filter(id=self.id).values(*put_back)[0]
177 logging.error("Unable to read %s from %s" % (", ".join(put_back), self.__class__.__name__))
180 self.reset_original_state()
184 cache.set(self.cache_key(self.id), self._as_dict(), 60 * 60)
187 cache.delete(self.cache_key(self.id))
191 super(BaseModel, self).delete()
194 from user import User
195 from node import Node, NodeRevision, NodeManager
196 from action import Action