1 from UserDict import DictMixin
3 from django import forms
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.contenttypes import generic
6 from django.core.exceptions import ObjectDoesNotExist
7 from django.core.validators import RegexValidator
8 from django.db import models
9 from django.utils import simplejson as json
10 from django.utils.encoding import force_unicode
11 from mptt.models import MPTTModel, MPTTModelBase, MPTTOptions
13 from philo.exceptions import AncestorDoesNotExist
14 from philo.models.fields import JSONField
15 from philo.signals import entity_class_prepared
16 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
17 from philo.validators import json_validator
20 class Tag(models.Model):
21 """A simple, generic model for tagging."""
22 #: A CharField (max length 255) which contains the name of the tag.
23 name = models.CharField(max_length=255)
24 #: A CharField (max length 255) which contains the tag's unique slug.
25 slug = models.SlugField(max_length=255, unique=True)
27 def __unicode__(self):
28 """Returns the value of the :attr:`name` field"""
36 class Titled(models.Model):
37 title = models.CharField(max_length=255)
38 slug = models.SlugField(max_length=255)
40 def __unicode__(self):
47 #: An instance of :class:`ContentTypeRegistryLimiter` which is used to track the content types which can be related to by :class:`ForeignKeyValue`\ s and :class:`ManyToManyValue`\ s.
48 value_content_type_limiter = ContentTypeRegistryLimiter()
51 def register_value_model(model):
52 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
53 value_content_type_limiter.register_class(model)
56 register_value_model(Tag)
59 def unregister_value_model(model):
60 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
61 value_content_type_limiter.unregister_class(model)
64 class AttributeValue(models.Model):
66 This is an abstract base class for models that can be used as values for :class:`Attribute`\ s.
68 AttributeValue subclasses are expected to supply access to a clean version of their value through an attribute called "value".
72 #: :class:`GenericRelation` to :class:`Attribute`
73 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
75 def set_value(self, value):
76 """Given a ``value``, sets the appropriate fields so that it can be correctly stored in the database."""
77 raise NotImplementedError
79 def value_formfields(self, **kwargs):
81 Returns any formfields that would be used to construct an instance of this value.
83 :returns: A dictionary mapping field names to formfields.
87 raise NotImplementedError
89 def construct_instance(self, **kwargs):
90 """Applies cleaned data from the formfields generated by valid_formfields to oneself."""
91 raise NotImplementedError
93 def __unicode__(self):
94 return unicode(self.value)
100 #: An instance of :class:`ContentTypeSubclassLimiter` which is used to track the content types which are considered valid value models for an :class:`Attribute`.
101 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
104 class JSONValue(AttributeValue):
105 """Stores a python object as a json string."""
106 value = JSONField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.', default='null', db_index=True)
108 def __unicode__(self):
109 return force_unicode(self.value)
111 def value_formfields(self):
112 kwargs = {'initial': self.value_json}
113 field = self._meta.get_field('value')
114 return {field.name: field.formfield(**kwargs)}
116 def construct_instance(self, **kwargs):
117 field_name = self._meta.get_field('value').name
118 self.set_value(kwargs.pop(field_name, None))
120 def set_value(self, value):
127 class ForeignKeyValue(AttributeValue):
128 """Stores a generic relationship to an instance of any value content type (as defined by the :data:`value_content_type_limiter`)."""
129 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
130 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
131 value = generic.GenericForeignKey()
133 def value_formfields(self):
134 field = self._meta.get_field('content_type')
135 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
137 if self.content_type:
139 'initial': self.object_id,
141 'queryset': self.content_type.model_class()._default_manager.all()
143 fields['value'] = forms.ModelChoiceField(**kwargs)
146 def construct_instance(self, **kwargs):
147 field_name = self._meta.get_field('content_type').name
148 ct = kwargs.pop(field_name, None)
149 if ct is None or ct != self.content_type:
150 self.object_id = None
151 self.content_type = ct
153 value = kwargs.pop('value', None)
154 self.set_value(value)
156 self.content_type = ct
158 def set_value(self, value):
165 class ManyToManyValue(AttributeValue):
166 """Stores a generic relationship to many instances of any value content type (as defined by the :data:`value_content_type_limiter`)."""
167 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
168 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
170 def get_object_ids(self):
171 return self.values.values_list('object_id', flat=True)
172 object_ids = property(get_object_ids)
174 def set_value(self, value):
175 # Value must be a queryset. Watch out for ModelMultipleChoiceField;
176 # it returns its value as a list if empty.
178 self.content_type = ContentType.objects.get_for_model(value.model)
180 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
185 object_ids = value.values_list('id', flat=True)
187 # These lines shouldn't be necessary; however, if object_ids is an EmptyQuerySet,
188 # the code (specifically the object_id__in query) won't work without them. Unclear why...
189 # TODO: is this still the case?
191 self.values.all().delete()
193 self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
195 current_ids = self.object_ids
197 for object_id in object_ids:
198 if object_id in current_ids:
200 self.values.create(content_type=self.content_type, object_id=object_id)
203 if self.content_type is None:
206 # HACK to be safely explicit until http://code.djangoproject.com/ticket/15145 is resolved
207 object_ids = self.object_ids
208 manager = self.content_type.model_class()._default_manager
210 return manager.none()
211 return manager.filter(id__in=self.object_ids)
213 value = property(get_value, set_value)
215 def value_formfields(self):
216 field = self._meta.get_field('content_type')
217 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
219 if self.content_type:
221 'initial': self.object_ids,
223 'queryset': self.content_type.model_class()._default_manager.all()
225 fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
228 def construct_instance(self, **kwargs):
229 field_name = self._meta.get_field('content_type').name
230 ct = kwargs.pop(field_name, None)
231 if ct is None or ct != self.content_type:
233 self.content_type = ct
235 value = kwargs.get('value', None)
237 value = self.content_type.model_class()._default_manager.none()
238 self.set_value(value)
239 construct_instance.alters_data = True
245 class Attribute(models.Model):
246 """Represents an arbitrary key/value pair on an arbitrary :class:`Model` where the key consists of word characters and the value is a subclass of :class:`AttributeValue`."""
247 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
248 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID', db_index=True)
250 #: :class:`GenericForeignKey` to anything (generally an instance of an Entity subclass).
251 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
253 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)
254 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
256 #: :class:`GenericForeignKey` to an instance of a subclass of :class:`AttributeValue` as determined by the :data:`attribute_value_limiter`.
257 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
259 #: :class:`CharField` containing a key (up to 255 characters) consisting of alphanumeric characters and underscores.
260 key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
262 def __unicode__(self):
263 return u'"%s": %s' % (self.key, self.value)
267 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
270 class QuerySetMapper(object, DictMixin):
271 def __init__(self, queryset, passthrough=None):
272 self.queryset = queryset
273 self.passthrough = passthrough
275 def __getitem__(self, key):
277 value = self.queryset.get(key__exact=key).value
278 except ObjectDoesNotExist:
279 if self.passthrough is not None:
280 return self.passthrough.__getitem__(key)
283 if value is not None:
288 keys = set(self.queryset.values_list('key', flat=True).distinct())
289 if self.passthrough is not None:
290 keys |= set(self.passthrough.keys())
294 class EntityOptions(object):
295 def __init__(self, options):
296 if options is not None:
297 for key, value in options.__dict__.items():
298 setattr(self, key, value)
299 if not hasattr(self, 'proxy_fields'):
300 self.proxy_fields = []
302 def add_proxy_field(self, proxy_field):
303 self.proxy_fields.append(proxy_field)
306 class EntityBase(models.base.ModelBase):
307 def __new__(cls, name, bases, attrs):
308 entity_meta = attrs.pop('EntityMeta', None)
309 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
310 new.add_to_class('_entity_meta', EntityOptions(entity_meta))
311 entity_class_prepared.send(sender=new)
315 class EntityAttributeMapper(object, DictMixin):
316 def __init__(self, entity):
319 def get_attributes(self):
320 return self.entity.attribute_set.all()
322 def make_cache(self):
323 attributes = self.get_attributes()
327 value_lookups.setdefault(a.value_content_type, []).append(a.value_object_id)
331 for ct, pks in value_lookups.items():
332 values_bulk[ct] = ct.model_class().objects.in_bulk(pks)
334 self._cache = dict([(a.key, getattr(values_bulk[a.value_content_type].get(a.value_object_id), 'value', None)) for a in attributes])
336 def __getitem__(self, key):
337 if not hasattr(self, '_cache'):
339 return self._cache[key]
342 if not hasattr(self, '_cache'):
344 return self._cache.keys()
347 if not hasattr(self, '_cache'):
349 return self._cache.items()
352 if not hasattr(self, '_cache'):
354 return self._cache.values()
357 class Entity(models.Model):
358 """An abstract class that simplifies access to related attributes. Most models provided by Philo subclass Entity."""
359 __metaclass__ = EntityBase
361 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
364 def attributes(self):
366 Property that returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
370 >>> attr = entity.attribute_set.get(key='spam')
373 >>> entity.attributes['spam']
377 return EntityAttributeMapper(self)
383 class TreeManager(models.Manager):
384 use_for_related_fields = True
386 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
388 If ``absolute_result`` is ``True``, returns the object at ``path`` (starting at ``root``) or raises a :class:`DoesNotExist` exception. Otherwise, returns a tuple containing the deepest object found along ``path`` (or ``root`` if no deeper object is found) and the remainder of the path after that object as a string (or None if there is no remaining path).
390 .. note:: If you are looking for something with an exact path, it is faster to use absolute_result=True, unless the path depth is over ~40, in which case the high cost of the absolute query may make a binary search (i.e. non-absolute) faster.
392 .. note:: SQLite allows max of 64 tables in one join. That means the binary search will only work on paths with a max depth of 127 and the absolute fetch will only work to a max depth of (surprise!) 63. Larger depths could be handled, but since the common use case will not have a tree structure that deep, they are not.
394 :param path: The path of the object
395 :param root: The object which will be considered the root of the search
396 :param absolute_result: Whether to return an absolute result or do a binary search
397 :param pathsep: The path separator used in ``path``
398 :param field: The field on the model which should be queried for ``path`` segment matching.
399 :returns: An instance if absolute_result is True or (instance, remaining_path) otherwise.
403 segments = path.split(pathsep)
405 # Clean out blank segments. Handles multiple consecutive pathseps.
412 # Special-case a lack of segments. No queries necessary.
419 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
421 def make_query_kwargs(segments, root):
424 revsegs = list(segments)
427 for segment in revsegs:
428 kwargs["%s%s__exact" % (prefix, field)] = segment
432 kwargs[prefix[:-2]] = root
436 def find_obj(segments, depth, deepest_found=None):
437 if deepest_found is None:
440 deepest_level = deepest_found.get_level() + 1
442 deepest_level = deepest_found.get_level() - root.get_level()
444 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
445 except self.model.DoesNotExist:
446 if not deepest_level and depth > 1:
447 # make sure there's a root node...
450 # Try finding one with half the path since the deepest find.
451 depth = (deepest_level + depth)/2
453 if deepest_level == depth:
454 # This should happen if nothing is found with any part of the given path.
455 if root is not None and deepest_found is None:
456 return root, pathsep.join(segments)
459 return find_obj(segments, depth, deepest_found)
463 deepest_level = obj.get_level() + 1
465 deepest_level = obj.get_level() - root.get_level()
467 # Could there be a deeper one?
468 if obj.is_leaf_node():
469 return obj, pathsep.join(segments[deepest_level:]) or None
471 depth += (len(segments) - depth)/2 or len(segments) - depth
473 if depth > deepest_level + obj.get_descendant_count():
474 depth = deepest_level + obj.get_descendant_count()
476 if deepest_level == depth:
477 return obj, pathsep.join(segments[deepest_level:]) or None
480 return find_obj(segments, depth, obj)
481 except self.model.DoesNotExist:
482 # Then this was the deepest.
483 return obj, pathsep.join(segments[deepest_level:])
486 return self.get(**make_query_kwargs(segments, root))
488 # Try a modified binary search algorithm. Feed the root in so that query complexity
489 # can be reduced. It might be possible to weight the search towards the beginning
490 # of the path, since short paths are more likely, but how far forward? It would
491 # need to shift depending on len(segments) - perhaps logarithmically?
492 return find_obj(segments, len(segments)/2 or len(segments))
495 class TreeModel(MPTTModel):
496 objects = TreeManager()
497 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
498 slug = models.SlugField(max_length=255)
500 def get_path(self, root=None, pathsep='/', field='slug'):
502 :param root: Only return the path since this object.
503 :param pathsep: The path separator to use when constructing an instance's path
504 :param field: The field to pull path information from for each ancestor.
505 :returns: A string representation of an object's path.
512 if root is not None and not self.is_descendant_of(root):
513 raise AncestorDoesNotExist(root)
515 qs = self.get_ancestors(include_self=True)
518 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
520 return pathsep.join([getattr(parent, field, '?') for parent in qs])
521 path = property(get_path)
523 def __unicode__(self):
527 unique_together = (('parent', 'slug'),)
531 class TreeEntityBase(MPTTModelBase, EntityBase):
532 def __new__(meta, name, bases, attrs):
533 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
534 cls = EntityBase.__new__(meta, name, bases, attrs)
536 return meta.register(cls)
539 class TreeEntityAttributeMapper(EntityAttributeMapper):
540 def get_attributes(self):
541 ancestors = dict(self.entity.get_ancestors(include_self=True).values_list('pk', 'level'))
542 ct = ContentType.objects.get_for_model(self.entity)
543 return sorted(Attribute.objects.filter(entity_content_type=ct, entity_object_id__in=ancestors.keys()), key=lambda x: ancestors[x.entity_object_id])
546 class TreeEntity(Entity, TreeModel):
547 """An abstract subclass of Entity which represents a tree relationship."""
549 __metaclass__ = TreeEntityBase
552 def attributes(self):
554 Property that returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly. If an attribute with a given key is not related to the :class:`Entity`, then the object will check the parent's attributes.
558 >>> attr = entity.attribute_set.get(key='spam')
559 DoesNotExist: Attribute matching query does not exist.
560 >>> attr = entity.parent.attribute_set.get(key='spam')
563 >>> entity.attributes['spam']
569 return TreeEntityAttributeMapper(self)
570 return super(TreeEntity, self).attributes