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 Entity(models.Model):
316 """An abstract class that simplifies access to related attributes. Most models provided by Philo subclass Entity."""
317 __metaclass__ = EntityBase
319 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
322 def attributes(self):
324 Property that returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
328 >>> attr = entity.attribute_set.get(key='spam')
331 >>> entity.attributes['spam']
336 return QuerySetMapper(self.attribute_set.all())
342 class TreeManager(models.Manager):
343 use_for_related_fields = True
345 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
347 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).
349 .. 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.
351 .. 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.
353 :param path: The path of the object
354 :param root: The object which will be considered the root of the search
355 :param absolute_result: Whether to return an absolute result or do a binary search
356 :param pathsep: The path separator used in ``path``
357 :param field: The field on the model which should be queried for ``path`` segment matching.
358 :returns: An instance if ``absolute_result`` is ``True`` or an (instance, remaining_path) tuple otherwise.
359 :raises django.core.exceptions.ObjectDoesNotExist: if no object can be found matching the input parameters.
363 segments = path.split(pathsep)
365 # Clean out blank segments. Handles multiple consecutive pathseps.
372 # Special-case a lack of segments. No queries necessary.
379 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
381 def make_query_kwargs(segments, root):
384 revsegs = list(segments)
387 for segment in revsegs:
388 kwargs["%s%s__exact" % (prefix, field)] = segment
392 kwargs[prefix[:-2]] = root
396 def find_obj(segments, depth, deepest_found=None):
397 if deepest_found is None:
400 deepest_level = deepest_found.get_level() + 1
402 deepest_level = deepest_found.get_level() - root.get_level()
404 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
405 except self.model.DoesNotExist:
406 if not deepest_level and depth > 1:
407 # make sure there's a root node...
410 # Try finding one with half the path since the deepest find.
411 depth = (deepest_level + depth)/2
413 if deepest_level == depth:
414 # This should happen if nothing is found with any part of the given path.
415 if root is not None and deepest_found is None:
416 return root, pathsep.join(segments)
419 return find_obj(segments, depth, deepest_found)
423 deepest_level = obj.get_level() + 1
425 deepest_level = obj.get_level() - root.get_level()
427 # Could there be a deeper one?
428 if obj.is_leaf_node():
429 return obj, pathsep.join(segments[deepest_level:]) or None
431 depth += (len(segments) - depth)/2 or len(segments) - depth
433 if depth > deepest_level + obj.get_descendant_count():
434 depth = deepest_level + obj.get_descendant_count()
436 if deepest_level == depth:
437 return obj, pathsep.join(segments[deepest_level:]) or None
440 return find_obj(segments, depth, obj)
441 except self.model.DoesNotExist:
442 # Then this was the deepest.
443 return obj, pathsep.join(segments[deepest_level:])
446 return self.get(**make_query_kwargs(segments, root))
448 # Try a modified binary search algorithm. Feed the root in so that query complexity
449 # can be reduced. It might be possible to weight the search towards the beginning
450 # of the path, since short paths are more likely, but how far forward? It would
451 # need to shift depending on len(segments) - perhaps logarithmically?
452 return find_obj(segments, len(segments)/2 or len(segments))
455 class TreeModel(MPTTModel):
456 objects = TreeManager()
457 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
458 slug = models.SlugField(max_length=255)
460 def get_path(self, root=None, pathsep='/', field='slug'):
462 :param root: Only return the path since this object.
463 :param pathsep: The path separator to use when constructing an instance's path
464 :param field: The field to pull path information from for each ancestor.
465 :returns: A string representation of an object's path.
472 if root is not None and not self.is_descendant_of(root):
473 raise AncestorDoesNotExist(root)
475 qs = self.get_ancestors(include_self=True)
478 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
480 return pathsep.join([getattr(parent, field, '?') for parent in qs])
481 path = property(get_path)
483 def __unicode__(self):
487 unique_together = (('parent', 'slug'),)
491 class TreeEntityBase(MPTTModelBase, EntityBase):
492 def __new__(meta, name, bases, attrs):
493 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
494 cls = EntityBase.__new__(meta, name, bases, attrs)
496 return meta.register(cls)
499 class TreeEntity(Entity, TreeModel):
500 """An abstract subclass of Entity which represents a tree relationship."""
502 __metaclass__ = TreeEntityBase
505 def attributes(self):
507 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.
511 >>> attr = entity.attribute_set.get(key='spam')
512 DoesNotExist: Attribute matching query does not exist.
513 >>> attr = entity.parent.attribute_set.get(key='spam')
516 >>> entity.attributes['spam']
522 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
523 return super(TreeEntity, self).attributes