1 from django import forms
2 from django.db import models
3 from django.contrib.contenttypes.models import ContentType
4 from django.contrib.contenttypes import generic
5 from django.utils import simplejson as json
6 from django.core.exceptions import ObjectDoesNotExist
7 from philo.exceptions import AncestorDoesNotExist
8 from philo.models.fields import JSONField
9 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
10 from philo.signals import entity_class_prepared
11 from philo.validators import json_validator
12 from UserDict import DictMixin
13 from mptt.models import MPTTModel, MPTTModelBase, MPTTOptions
16 class Tag(models.Model):
17 name = models.CharField(max_length=255)
18 slug = models.SlugField(max_length=255, unique=True)
20 def __unicode__(self):
27 class Titled(models.Model):
28 title = models.CharField(max_length=255)
29 slug = models.SlugField(max_length=255)
31 def __unicode__(self):
38 value_content_type_limiter = ContentTypeRegistryLimiter()
41 def register_value_model(model):
42 value_content_type_limiter.register_class(model)
45 def unregister_value_model(model):
46 value_content_type_limiter.unregister_class(model)
49 class AttributeValue(models.Model):
50 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
54 return self.attribute_set.all()[0]
56 def apply_data(self, data):
57 raise NotImplementedError
59 def value_formfield(self, **kwargs):
60 raise NotImplementedError
62 def __unicode__(self):
63 return unicode(self.value)
69 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
72 class JSONValue(AttributeValue):
73 value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
75 def __unicode__(self):
76 return self.value_json
78 def value_formfield(self, **kwargs):
79 kwargs['initial'] = self.value_json
80 return self._meta.get_field('value').formfield(**kwargs)
82 def apply_data(self, cleaned_data):
83 self.value = cleaned_data.get('value', None)
89 class ForeignKeyValue(AttributeValue):
90 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
91 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
92 value = generic.GenericForeignKey()
94 def value_formfield(self, form_class=forms.ModelChoiceField, **kwargs):
95 if self.content_type is None:
97 kwargs.update({'initial': self.object_id, 'required': False})
98 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
100 def apply_data(self, cleaned_data):
101 if 'value' in cleaned_data and cleaned_data['value'] is not None:
102 self.value = cleaned_data['value']
104 self.content_type = cleaned_data.get('content_type', None)
105 # If there is no value set in the cleaned data, clear the stored value.
106 self.object_id = None
112 class ManyToManyValue(AttributeValue):
113 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
114 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
116 def get_object_id_list(self):
117 if not self.values.count():
120 return self.values.values_list('object_id', flat=True)
123 if self.content_type is None:
126 return self.content_type.model_class()._default_manager.filter(id__in=self.get_object_id_list())
128 def set_value(self, value):
129 # Value is probably a queryset - but allow any iterable.
131 # These lines shouldn't be necessary; however, if value is an EmptyQuerySet,
132 # the code (specifically the object_id__in query) won't work without them. Unclear why...
136 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
141 if isinstance(value, models.query.QuerySet):
142 value = value.values_list('id', flat=True)
144 self.values.filter(~models.Q(object_id__in=value)).delete()
145 current = self.get_object_id_list()
150 self.values.create(content_type=self.content_type, object_id=v)
152 value = property(get_value, set_value)
154 def value_formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
155 if self.content_type is None:
157 kwargs.update({'initial': self.get_object_id_list(), 'required': False})
158 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
160 def apply_data(self, cleaned_data):
161 if 'value' in cleaned_data and cleaned_data['value'] is not None:
162 self.value = cleaned_data['value']
164 self.content_type = cleaned_data.get('content_type', None)
165 # If there is no value set in the cleaned data, clear the stored value.
172 class Attribute(models.Model):
173 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
174 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
175 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
177 value_content_type = models.ForeignKey(ContentType, related_name='attribute_value_set', limit_choices_to=attribute_value_limiter, verbose_name='Value type', null=True, blank=True)
178 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
179 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
181 key = models.CharField(max_length=255)
183 def __unicode__(self):
184 return u'"%s": %s' % (self.key, self.value)
188 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
191 class QuerySetMapper(object, DictMixin):
192 def __init__(self, queryset, passthrough=None):
193 self.queryset = queryset
194 self.passthrough = passthrough
196 def __getitem__(self, key):
198 value = self.queryset.get(key__exact=key).value
199 except ObjectDoesNotExist:
200 if self.passthrough is not None:
201 return self.passthrough.__getitem__(key)
204 if value is not None:
209 keys = set(self.queryset.values_list('key', flat=True).distinct())
210 if self.passthrough is not None:
211 keys |= set(self.passthrough.keys())
215 class EntityOptions(object):
216 def __init__(self, options):
217 if options is not None:
218 for key, value in options.__dict__.items():
219 setattr(self, key, value)
220 if not hasattr(self, 'proxy_fields'):
221 self.proxy_fields = []
223 def add_proxy_field(self, proxy_field):
224 self.proxy_fields.append(proxy_field)
227 class EntityBase(models.base.ModelBase):
228 def __new__(cls, name, bases, attrs):
229 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
230 entity_options = attrs.pop('EntityMeta', None)
231 setattr(new, '_entity_meta', EntityOptions(entity_options))
232 entity_class_prepared.send(sender=new)
236 class Entity(models.Model):
237 __metaclass__ = EntityBase
239 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
242 def attributes(self):
243 return QuerySetMapper(self.attribute_set.all())
246 def _added_attribute_registry(self):
247 if not hasattr(self, '_real_added_attribute_registry'):
248 self._real_added_attribute_registry = {}
249 return self._real_added_attribute_registry
252 def _removed_attribute_registry(self):
253 if not hasattr(self, '_real_removed_attribute_registry'):
254 self._real_removed_attribute_registry = []
255 return self._real_removed_attribute_registry
257 def save(self, *args, **kwargs):
258 super(Entity, self).save(*args, **kwargs)
260 for key in self._removed_attribute_registry:
261 self.attribute_set.filter(key__exact=key).delete()
262 del self._removed_attribute_registry[:]
264 for field, value in self._added_attribute_registry.items():
266 attribute = self.attribute_set.get(key__exact=field.key)
267 except Attribute.DoesNotExist:
268 attribute = Attribute()
269 attribute.entity = self
270 attribute.key = field.key
272 field.set_attribute_value(attribute, value)
274 self._added_attribute_registry.clear()
280 class TreeManager(models.Manager):
281 use_for_related_fields = True
283 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
285 Returns the object with the path, unless absolute_result is set to False, in which
286 case it returns a tuple containing the deepest object found along the path, and the
287 remainder of the path after that object as a string (or None if there is no remaining
288 path). Raises a DoesNotExist exception if no object is found with the given path.
290 If the path you're searching for is known to exist, it is always faster to use
291 absolute_result=True - unless the path depth is over ~40, in which case the high cost
292 of the absolute query makes a binary search (i.e. non-absolute) faster.
294 # Note: SQLite allows max of 64 tables in one join. That means the binary search will
295 # only work on paths with a max depth of 127 and the absolute fetch will only work
296 # to a max depth of (surprise!) 63. Although this could be handled, chances are your
297 # tree structure won't be that deep.
298 segments = path.split(pathsep)
300 # Check for a trailing pathsep so we can restore it later.
301 trailing_pathsep = False
302 if segments[-1] == '':
303 trailing_pathsep = True
305 # Clean out blank segments. Handles multiple consecutive pathseps.
312 # Special-case a lack of segments. No queries necessary.
319 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
321 def make_query_kwargs(segments, root):
324 revsegs = list(segments)
327 for segment in revsegs:
328 kwargs["%s%s__exact" % (prefix, field)] = segment
332 kwargs[prefix[:-2]] = root
336 def build_path(segments):
337 path = pathsep.join(segments)
338 if trailing_pathsep and segments and segments[-1] != '':
342 def find_obj(segments, depth, deepest_found=None):
343 if deepest_found is None:
346 deepest_level = deepest_found.get_level() + 1
348 deepest_level = deepest_found.get_level() - root.get_level()
350 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
351 except self.model.DoesNotExist:
352 if not deepest_level and depth > 1:
353 # make sure there's a root node...
356 # Try finding one with half the path since the deepest find.
357 depth = (deepest_level + depth)/2
359 if deepest_level == depth:
360 # This should happen if nothing is found with any part of the given path.
363 return find_obj(segments, depth, deepest_found)
367 deepest_level = obj.get_level() + 1
369 deepest_level = obj.get_level() - root.get_level()
371 # Could there be a deeper one?
372 if obj.is_leaf_node():
373 return obj, build_path(segments[deepest_level:]) or None
375 depth += (len(segments) - depth)/2 or len(segments) - depth
377 if depth > deepest_level + obj.get_descendant_count():
378 depth = deepest_level + obj.get_descendant_count()
380 if deepest_level == depth:
381 return obj, build_path(segments[deepest_level:]) or None
384 return find_obj(segments, depth, obj)
385 except self.model.DoesNotExist:
386 # Then this was the deepest.
387 return obj, build_path(segments[deepest_level:])
390 return self.get(**make_query_kwargs(segments, root))
392 # Try a modified binary search algorithm. Feed the root in so that query complexity
393 # can be reduced. It might be possible to weight the search towards the beginning
394 # of the path, since short paths are more likely, but how far forward? It would
395 # need to shift depending on len(segments) - perhaps logarithmically?
396 return find_obj(segments, len(segments)/2 or len(segments))
399 class TreeModel(MPTTModel):
400 objects = TreeManager()
401 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
402 slug = models.SlugField(max_length=255)
404 def get_path(self, root=None, pathsep='/', field='slug'):
408 if root is not None and not self.is_descendant_of(root):
409 raise AncestorDoesNotExist(root)
411 qs = self.get_ancestors()
414 qs = qs.filter(level__gt=root.level)
416 return pathsep.join([getattr(parent, field, '?') for parent in list(qs) + [self]])
417 path = property(get_path)
419 def __unicode__(self):
423 unique_together = (('parent', 'slug'),)
427 class TreeEntityBase(MPTTModelBase, EntityBase):
428 def __new__(meta, name, bases, attrs):
429 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
430 cls = EntityBase.__new__(meta, name, bases, attrs)
432 return meta.register(cls)
435 class TreeEntity(Entity, TreeModel):
436 __metaclass__ = TreeEntityBase
439 def attributes(self):
441 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
442 return super(TreeEntity, self).attributes