1 from django import forms
2 from django.contrib.contenttypes.models import ContentType
3 from django.contrib.contenttypes import generic
4 from django.core.exceptions import ObjectDoesNotExist
5 from django.core.validators import RegexValidator
6 from django.db import models
7 from django.utils import simplejson as json
8 from django.utils.encoding import force_unicode
9 from mptt.models import MPTTModel, MPTTModelBase, MPTTOptions
11 from philo.exceptions import AncestorDoesNotExist
12 from philo.models.fields import JSONField
13 from philo.signals import entity_class_prepared
14 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
15 from philo.utils.entities import AttributeMapper, TreeAttributeMapper
16 from philo.validators import json_validator
19 class Tag(models.Model):
20 """A simple, generic model for tagging."""
21 #: A CharField (max length 255) which contains the name of the tag.
22 name = models.CharField(max_length=255)
23 #: A CharField (max length 255) which contains the tag's unique slug.
24 slug = models.SlugField(max_length=255, unique=True)
26 def __unicode__(self):
27 """Returns the value of the :attr:`name` field"""
35 class Titled(models.Model):
36 title = models.CharField(max_length=255)
37 slug = models.SlugField(max_length=255)
39 def __unicode__(self):
46 #: 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.
47 value_content_type_limiter = ContentTypeRegistryLimiter()
50 def register_value_model(model):
51 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
52 value_content_type_limiter.register_class(model)
55 register_value_model(Tag)
58 def unregister_value_model(model):
59 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
60 value_content_type_limiter.unregister_class(model)
63 class AttributeValue(models.Model):
65 This is an abstract base class for models that can be used as values for :class:`Attribute`\ s.
67 AttributeValue subclasses are expected to supply access to a clean version of their value through an attribute called "value".
71 #: :class:`GenericRelation` to :class:`Attribute`
72 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
74 def set_value(self, value):
75 """Given a ``value``, sets the appropriate fields so that it can be correctly stored in the database."""
76 raise NotImplementedError
78 def value_formfields(self, **kwargs):
80 Returns any formfields that would be used to construct an instance of this value.
82 :returns: A dictionary mapping field names to formfields.
86 raise NotImplementedError
88 def construct_instance(self, **kwargs):
89 """Applies cleaned data from the formfields generated by valid_formfields to oneself."""
90 raise NotImplementedError
92 def __unicode__(self):
93 return unicode(self.value)
99 #: An instance of :class:`ContentTypeSubclassLimiter` which is used to track the content types which are considered valid value models for an :class:`Attribute`.
100 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
103 class JSONValue(AttributeValue):
104 """Stores a python object as a json string."""
105 value = JSONField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.', default='null', db_index=True)
107 def __unicode__(self):
108 return force_unicode(self.value)
110 def value_formfields(self):
111 kwargs = {'initial': self.value_json}
112 field = self._meta.get_field('value')
113 return {field.name: field.formfield(**kwargs)}
115 def construct_instance(self, **kwargs):
116 field_name = self._meta.get_field('value').name
117 self.set_value(kwargs.pop(field_name, None))
119 def set_value(self, value):
126 class ForeignKeyValue(AttributeValue):
127 """Stores a generic relationship to an instance of any value content type (as defined by the :data:`value_content_type_limiter`)."""
128 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
129 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
130 value = generic.GenericForeignKey()
132 def value_formfields(self):
133 field = self._meta.get_field('content_type')
134 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
136 if self.content_type:
138 'initial': self.object_id,
140 'queryset': self.content_type.model_class()._default_manager.all()
142 fields['value'] = forms.ModelChoiceField(**kwargs)
145 def construct_instance(self, **kwargs):
146 field_name = self._meta.get_field('content_type').name
147 ct = kwargs.pop(field_name, None)
148 if ct is None or ct != self.content_type:
149 self.object_id = None
150 self.content_type = ct
152 value = kwargs.pop('value', None)
153 self.set_value(value)
155 self.content_type = ct
157 def set_value(self, value):
164 class ManyToManyValue(AttributeValue):
165 """Stores a generic relationship to many instances of any value content type (as defined by the :data:`value_content_type_limiter`)."""
166 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
167 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
169 def get_object_ids(self):
170 return self.values.values_list('object_id', flat=True)
171 object_ids = property(get_object_ids)
173 def set_value(self, value):
174 # Value must be a queryset. Watch out for ModelMultipleChoiceField;
175 # it returns its value as a list if empty.
177 self.content_type = ContentType.objects.get_for_model(value.model)
179 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
184 object_ids = value.values_list('id', flat=True)
186 # These lines shouldn't be necessary; however, if object_ids is an EmptyQuerySet,
187 # the code (specifically the object_id__in query) won't work without them. Unclear why...
188 # TODO: is this still the case?
190 self.values.all().delete()
192 self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
194 current_ids = self.object_ids
196 for object_id in object_ids:
197 if object_id in current_ids:
199 self.values.create(content_type=self.content_type, object_id=object_id)
202 if self.content_type is None:
205 # HACK to be safely explicit until http://code.djangoproject.com/ticket/15145 is resolved
206 object_ids = self.object_ids
207 manager = self.content_type.model_class()._default_manager
209 return manager.none()
210 return manager.filter(id__in=self.object_ids)
212 value = property(get_value, set_value)
214 def value_formfields(self):
215 field = self._meta.get_field('content_type')
216 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
218 if self.content_type:
220 'initial': self.object_ids,
222 'queryset': self.content_type.model_class()._default_manager.all()
224 fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
227 def construct_instance(self, **kwargs):
228 field_name = self._meta.get_field('content_type').name
229 ct = kwargs.pop(field_name, None)
230 if ct is None or ct != self.content_type:
232 self.content_type = ct
234 value = kwargs.get('value', None)
236 value = self.content_type.model_class()._default_manager.none()
237 self.set_value(value)
238 construct_instance.alters_data = True
244 class Attribute(models.Model):
245 """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`."""
246 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
247 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID', db_index=True)
249 #: :class:`GenericForeignKey` to anything (generally an instance of an Entity subclass).
250 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
252 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)
253 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
255 #: :class:`GenericForeignKey` to an instance of a subclass of :class:`AttributeValue` as determined by the :data:`attribute_value_limiter`.
256 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
258 #: :class:`CharField` containing a key (up to 255 characters) consisting of alphanumeric characters and underscores.
259 key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
261 def __unicode__(self):
262 return u'"%s": %s' % (self.key, self.value)
264 def set_value(self, value, value_class=JSONValue):
265 """Given a value and a value class, sets up self.value appropriately."""
266 if isinstance(self.value, value_class):
269 if isinstance(self.value, models.Model):
281 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
284 class EntityOptions(object):
285 def __init__(self, options):
286 if options is not None:
287 for key, value in options.__dict__.items():
288 setattr(self, key, value)
289 if not hasattr(self, 'proxy_fields'):
290 self.proxy_fields = []
292 def add_proxy_field(self, proxy_field):
293 self.proxy_fields.append(proxy_field)
296 class EntityBase(models.base.ModelBase):
297 def __new__(cls, name, bases, attrs):
298 entity_meta = attrs.pop('EntityMeta', None)
299 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
300 new.add_to_class('_entity_meta', EntityOptions(entity_meta))
301 entity_class_prepared.send(sender=new)
305 class Entity(models.Model):
306 """An abstract class that simplifies access to related attributes. Most models provided by Philo subclass Entity."""
307 __metaclass__ = EntityBase
309 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
311 def get_attribute_mapper(self, mapper=AttributeMapper):
313 Returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
317 >>> attr = entity.attribute_set.get(key='spam')
320 >>> entity.attributes['spam']
325 attributes = property(get_attribute_mapper)
331 class TreeManager(models.Manager):
332 use_for_related_fields = True
334 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
336 If ``absolute_result`` is ``True``, returns the object at ``path`` (starting at ``root``) or raises an :class:`~django.core.exceptions.ObjectDoesNotExist` 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).
338 .. 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.
340 .. 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.
342 :param path: The path of the object
343 :param root: The object which will be considered the root of the search
344 :param absolute_result: Whether to return an absolute result or do a binary search
345 :param pathsep: The path separator used in ``path``
346 :param field: The field on the model which should be queried for ``path`` segment matching.
347 :returns: An instance if ``absolute_result`` is ``True`` or an (instance, remaining_path) tuple otherwise.
348 :raises django.core.exceptions.ObjectDoesNotExist: if no object can be found matching the input parameters.
352 segments = path.split(pathsep)
354 # Clean out blank segments. Handles multiple consecutive pathseps.
361 # Special-case a lack of segments. No queries necessary.
368 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
370 def make_query_kwargs(segments, root):
373 revsegs = list(segments)
376 for segment in revsegs:
377 kwargs["%s%s__exact" % (prefix, field)] = segment
381 kwargs[prefix[:-2]] = root
385 def find_obj(segments, depth, deepest_found=None):
386 if deepest_found is None:
389 deepest_level = deepest_found.get_level() + 1
391 deepest_level = deepest_found.get_level() - root.get_level()
393 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
394 except self.model.DoesNotExist:
395 if not deepest_level and depth > 1:
396 # make sure there's a root node...
399 # Try finding one with half the path since the deepest find.
400 depth = (deepest_level + depth)/2
402 if deepest_level == depth:
403 # This should happen if nothing is found with any part of the given path.
404 if root is not None and deepest_found is None:
405 return root, pathsep.join(segments)
408 return find_obj(segments, depth, deepest_found)
412 deepest_level = obj.get_level() + 1
414 deepest_level = obj.get_level() - root.get_level()
416 # Could there be a deeper one?
417 if obj.is_leaf_node():
418 return obj, pathsep.join(segments[deepest_level:]) or None
420 depth += (len(segments) - depth)/2 or len(segments) - depth
422 if depth > deepest_level + obj.get_descendant_count():
423 depth = deepest_level + obj.get_descendant_count()
425 if deepest_level == depth:
426 return obj, pathsep.join(segments[deepest_level:]) or None
429 return find_obj(segments, depth, obj)
430 except self.model.DoesNotExist:
431 # Then this was the deepest.
432 return obj, pathsep.join(segments[deepest_level:])
435 return self.get(**make_query_kwargs(segments, root))
437 # Try a modified binary search algorithm. Feed the root in so that query complexity
438 # can be reduced. It might be possible to weight the search towards the beginning
439 # of the path, since short paths are more likely, but how far forward? It would
440 # need to shift depending on len(segments) - perhaps logarithmically?
441 return find_obj(segments, len(segments)/2 or len(segments))
444 class TreeModel(MPTTModel):
445 objects = TreeManager()
446 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
447 slug = models.SlugField(max_length=255)
449 def get_path(self, root=None, pathsep='/', field='slug'):
451 :param root: Only return the path since this object.
452 :param pathsep: The path separator to use when constructing an instance's path
453 :param field: The field to pull path information from for each ancestor.
454 :returns: A string representation of an object's path.
461 if root is not None and not self.is_descendant_of(root):
462 raise AncestorDoesNotExist(root)
464 qs = self.get_ancestors(include_self=True)
467 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
469 return pathsep.join([getattr(parent, field, '?') for parent in qs])
470 path = property(get_path)
472 def __unicode__(self):
476 unique_together = (('parent', 'slug'),)
480 class TreeEntityBase(MPTTModelBase, EntityBase):
481 def __new__(meta, name, bases, attrs):
482 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
483 cls = EntityBase.__new__(meta, name, bases, attrs)
485 return meta.register(cls)
488 class TreeEntity(Entity, TreeModel):
489 """An abstract subclass of Entity which represents a tree relationship."""
491 __metaclass__ = TreeEntityBase
493 def get_attribute_mapper(self, mapper=None):
495 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.
499 >>> attr = entity.attribute_set.get(key='spam')
500 DoesNotExist: Attribute matching query does not exist.
501 >>> attr = entity.parent.attribute_set.get(key='spam')
504 >>> entity.attributes['spam']
510 mapper = TreeAttributeMapper
512 mapper = AttributeMapper
513 return super(TreeEntity, self).get_attribute_mapper(mapper)
514 attributes = property(get_attribute_mapper)