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.core.exceptions import ObjectDoesNotExist
6 from django.utils import simplejson as json
7 from django.utils.encoding import smart_str
8 from philo.exceptions import AncestorDoesNotExist
9 from philo.models.fields import JSONField
10 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
11 from philo.signals import entity_class_prepared
12 from philo.validators import json_validator
13 from UserDict import DictMixin
14 from mptt.models import MPTTModel, MPTTModelBase, MPTTOptions
17 class Tag(models.Model):
18 name = models.CharField(max_length=255)
19 slug = models.SlugField(max_length=255, unique=True)
21 def __unicode__(self):
28 class Titled(models.Model):
29 title = models.CharField(max_length=255)
30 slug = models.SlugField(max_length=255)
32 def __unicode__(self):
39 value_content_type_limiter = ContentTypeRegistryLimiter()
42 def register_value_model(model):
43 value_content_type_limiter.register_class(model)
46 def unregister_value_model(model):
47 value_content_type_limiter.unregister_class(model)
50 class AttributeValue(models.Model):
51 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
55 return self.attribute_set.all()[0]
57 def apply_data(self, data):
58 raise NotImplementedError
60 def value_formfield(self, **kwargs):
61 raise NotImplementedError
63 def __unicode__(self):
64 return unicode(self.value)
70 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
73 class JSONValue(AttributeValue):
74 value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
76 def __unicode__(self):
77 return smart_str(self.value)
79 def value_formfield(self, **kwargs):
80 kwargs['initial'] = self.value_json
81 return self._meta.get_field('value').formfield(**kwargs)
83 def apply_data(self, cleaned_data):
84 self.value = cleaned_data.get('value', None)
90 class ForeignKeyValue(AttributeValue):
91 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
92 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
93 value = generic.GenericForeignKey()
95 def value_formfield(self, form_class=forms.ModelChoiceField, **kwargs):
96 if self.content_type is None:
98 kwargs.update({'initial': self.object_id, 'required': False})
99 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
101 def apply_data(self, cleaned_data):
102 if 'value' in cleaned_data and cleaned_data['value'] is not None:
103 self.value = cleaned_data['value']
105 self.content_type = cleaned_data.get('content_type', None)
106 # If there is no value set in the cleaned data, clear the stored value.
107 self.object_id = None
113 class ManyToManyValue(AttributeValue):
114 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
115 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
117 def get_object_id_list(self):
118 if not self.values.count():
121 return self.values.values_list('object_id', flat=True)
124 if self.content_type is None:
127 return self.content_type.model_class()._default_manager.filter(id__in=self.get_object_id_list())
129 def set_value(self, value):
130 # Value is probably a queryset - but allow any iterable.
132 # These lines shouldn't be necessary; however, if value is an EmptyQuerySet,
133 # the code (specifically the object_id__in query) won't work without them. Unclear why...
137 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
142 if isinstance(value, models.query.QuerySet):
143 value = value.values_list('id', flat=True)
145 self.values.filter(~models.Q(object_id__in=value)).delete()
146 current = self.get_object_id_list()
151 self.values.create(content_type=self.content_type, object_id=v)
153 value = property(get_value, set_value)
155 def value_formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
156 if self.content_type is None:
158 kwargs.update({'initial': self.get_object_id_list(), 'required': False})
159 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
161 def apply_data(self, cleaned_data):
162 if 'value' in cleaned_data and cleaned_data['value'] is not None:
163 self.value = cleaned_data['value']
165 self.content_type = cleaned_data.get('content_type', None)
166 # If there is no value set in the cleaned data, clear the stored value.
173 class Attribute(models.Model):
174 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
175 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
176 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
178 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)
179 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
180 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
182 key = models.CharField(max_length=255)
184 def __unicode__(self):
185 return u'"%s": %s' % (self.key, self.value)
189 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
192 class QuerySetMapper(object, DictMixin):
193 def __init__(self, queryset, passthrough=None):
194 self.queryset = queryset
195 self.passthrough = passthrough
197 def __getitem__(self, key):
199 value = self.queryset.get(key__exact=key).value
200 except ObjectDoesNotExist:
201 if self.passthrough is not None:
202 return self.passthrough.__getitem__(key)
205 if value is not None:
210 keys = set(self.queryset.values_list('key', flat=True).distinct())
211 if self.passthrough is not None:
212 keys |= set(self.passthrough.keys())
216 class EntityOptions(object):
217 def __init__(self, options):
218 if options is not None:
219 for key, value in options.__dict__.items():
220 setattr(self, key, value)
221 if not hasattr(self, 'proxy_fields'):
222 self.proxy_fields = []
224 def add_proxy_field(self, proxy_field):
225 self.proxy_fields.append(proxy_field)
228 class EntityBase(models.base.ModelBase):
229 def __new__(cls, name, bases, attrs):
230 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
231 entity_options = attrs.pop('EntityMeta', None)
232 setattr(new, '_entity_meta', EntityOptions(entity_options))
233 entity_class_prepared.send(sender=new)
237 class Entity(models.Model):
238 __metaclass__ = EntityBase
240 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
243 def attributes(self):
244 return QuerySetMapper(self.attribute_set.all())
247 def _added_attribute_registry(self):
248 if not hasattr(self, '_real_added_attribute_registry'):
249 self._real_added_attribute_registry = {}
250 return self._real_added_attribute_registry
253 def _removed_attribute_registry(self):
254 if not hasattr(self, '_real_removed_attribute_registry'):
255 self._real_removed_attribute_registry = []
256 return self._real_removed_attribute_registry
258 def save(self, *args, **kwargs):
259 super(Entity, self).save(*args, **kwargs)
261 for key in self._removed_attribute_registry:
262 self.attribute_set.filter(key__exact=key).delete()
263 del self._removed_attribute_registry[:]
265 for field, value in self._added_attribute_registry.items():
267 attribute = self.attribute_set.get(key__exact=field.key)
268 except Attribute.DoesNotExist:
269 attribute = Attribute()
270 attribute.entity = self
271 attribute.key = field.key
273 field.set_attribute_value(attribute, value)
275 self._added_attribute_registry.clear()
281 class TreeManager(models.Manager):
282 use_for_related_fields = True
284 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
286 Returns the object with the path, unless absolute_result is set to False, in which
287 case it returns a tuple containing the deepest object found along the path, and the
288 remainder of the path after that object as a string (or None if there is no remaining
289 path). Raises a DoesNotExist exception if no object is found with the given path.
291 If the path you're searching for is known to exist, it is always faster to use
292 absolute_result=True - unless the path depth is over ~40, in which case the high cost
293 of the absolute query makes a binary search (i.e. non-absolute) faster.
295 # Note: SQLite allows max of 64 tables in one join. That means the binary search will
296 # only work on paths with a max depth of 127 and the absolute fetch will only work
297 # to a max depth of (surprise!) 63. Although this could be handled, chances are your
298 # tree structure won't be that deep.
299 segments = path.split(pathsep)
301 # Check for a trailing pathsep so we can restore it later.
302 trailing_pathsep = False
303 if segments[-1] == '':
304 trailing_pathsep = True
306 # Clean out blank segments. Handles multiple consecutive pathseps.
313 # Special-case a lack of segments. No queries necessary.
320 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
322 def make_query_kwargs(segments, root):
325 revsegs = list(segments)
328 for segment in revsegs:
329 kwargs["%s%s__exact" % (prefix, field)] = segment
333 kwargs[prefix[:-2]] = root
337 def build_path(segments):
338 path = pathsep.join(segments)
339 if trailing_pathsep and segments and segments[-1] != '':
343 def find_obj(segments, depth, deepest_found=None):
344 if deepest_found is None:
347 deepest_level = deepest_found.get_level() + 1
349 deepest_level = deepest_found.get_level() - root.get_level()
351 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
352 except self.model.DoesNotExist:
353 if not deepest_level and depth > 1:
354 # make sure there's a root node...
357 # Try finding one with half the path since the deepest find.
358 depth = (deepest_level + depth)/2
360 if deepest_level == depth:
361 # This should happen if nothing is found with any part of the given path.
362 if root is not None and deepest_found is None:
363 return root, build_path(segments)
366 return find_obj(segments, depth, deepest_found)
370 deepest_level = obj.get_level() + 1
372 deepest_level = obj.get_level() - root.get_level()
374 # Could there be a deeper one?
375 if obj.is_leaf_node():
376 return obj, build_path(segments[deepest_level:]) or None
378 depth += (len(segments) - depth)/2 or len(segments) - depth
380 if depth > deepest_level + obj.get_descendant_count():
381 depth = deepest_level + obj.get_descendant_count()
383 if deepest_level == depth:
384 return obj, build_path(segments[deepest_level:]) or None
387 return find_obj(segments, depth, obj)
388 except self.model.DoesNotExist:
389 # Then this was the deepest.
390 return obj, build_path(segments[deepest_level:])
393 return self.get(**make_query_kwargs(segments, root))
395 # Try a modified binary search algorithm. Feed the root in so that query complexity
396 # can be reduced. It might be possible to weight the search towards the beginning
397 # of the path, since short paths are more likely, but how far forward? It would
398 # need to shift depending on len(segments) - perhaps logarithmically?
399 return find_obj(segments, len(segments)/2 or len(segments))
402 class TreeModel(MPTTModel):
403 objects = TreeManager()
404 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
405 slug = models.SlugField(max_length=255)
407 def get_path(self, root=None, pathsep='/', field='slug'):
411 if root is not None and not self.is_descendant_of(root):
412 raise AncestorDoesNotExist(root)
414 qs = self.get_ancestors()
417 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
419 return pathsep.join([getattr(parent, field, '?') for parent in list(qs) + [self]])
420 path = property(get_path)
422 def __unicode__(self):
426 unique_together = (('parent', 'slug'),)
430 class TreeEntityBase(MPTTModelBase, EntityBase):
431 def __new__(meta, name, bases, attrs):
432 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
433 cls = EntityBase.__new__(meta, name, bases, attrs)
435 return meta.register(cls)
438 class TreeEntity(Entity, TreeModel):
439 __metaclass__ = TreeEntityBase
442 def attributes(self):
444 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
445 return super(TreeEntity, self).attributes