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 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).
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 (instance, remaining_path) otherwise.
362 segments = path.split(pathsep)
364 # Clean out blank segments. Handles multiple consecutive pathseps.
371 # Special-case a lack of segments. No queries necessary.
378 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
380 def make_query_kwargs(segments, root):
383 revsegs = list(segments)
386 for segment in revsegs:
387 kwargs["%s%s__exact" % (prefix, field)] = segment
391 kwargs[prefix[:-2]] = root
395 def find_obj(segments, depth, deepest_found=None):
396 if deepest_found is None:
399 deepest_level = deepest_found.get_level() + 1
401 deepest_level = deepest_found.get_level() - root.get_level()
403 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
404 except self.model.DoesNotExist:
405 if not deepest_level and depth > 1:
406 # make sure there's a root node...
409 # Try finding one with half the path since the deepest find.
410 depth = (deepest_level + depth)/2
412 if deepest_level == depth:
413 # This should happen if nothing is found with any part of the given path.
414 if root is not None and deepest_found is None:
415 return root, pathsep.join(segments)
418 return find_obj(segments, depth, deepest_found)
422 deepest_level = obj.get_level() + 1
424 deepest_level = obj.get_level() - root.get_level()
426 # Could there be a deeper one?
427 if obj.is_leaf_node():
428 return obj, pathsep.join(segments[deepest_level:]) or None
430 depth += (len(segments) - depth)/2 or len(segments) - depth
432 if depth > deepest_level + obj.get_descendant_count():
433 depth = deepest_level + obj.get_descendant_count()
435 if deepest_level == depth:
436 return obj, pathsep.join(segments[deepest_level:]) or None
439 return find_obj(segments, depth, obj)
440 except self.model.DoesNotExist:
441 # Then this was the deepest.
442 return obj, pathsep.join(segments[deepest_level:])
445 return self.get(**make_query_kwargs(segments, root))
447 # Try a modified binary search algorithm. Feed the root in so that query complexity
448 # can be reduced. It might be possible to weight the search towards the beginning
449 # of the path, since short paths are more likely, but how far forward? It would
450 # need to shift depending on len(segments) - perhaps logarithmically?
451 return find_obj(segments, len(segments)/2 or len(segments))
454 class TreeModel(MPTTModel):
455 objects = TreeManager()
456 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
457 slug = models.SlugField(max_length=255)
459 def get_path(self, root=None, pathsep='/', field='slug'):
461 :param root: Only return the path since this object.
462 :param pathsep: The path separator to use when constructing an instance's path
463 :param field: The field to pull path information from for each ancestor.
464 :returns: A string representation of an object's path.
471 if root is not None and not self.is_descendant_of(root):
472 raise AncestorDoesNotExist(root)
474 qs = self.get_ancestors(include_self=True)
477 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
479 return pathsep.join([getattr(parent, field, '?') for parent in qs])
480 path = property(get_path)
482 def __unicode__(self):
486 unique_together = (('parent', 'slug'),)
490 class TreeEntityBase(MPTTModelBase, EntityBase):
491 def __new__(meta, name, bases, attrs):
492 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
493 cls = EntityBase.__new__(meta, name, bases, attrs)
495 return meta.register(cls)
498 class TreeEntity(Entity, TreeModel):
499 """An abstract subclass of Entity which represents a tree relationship."""
501 __metaclass__ = TreeEntityBase
504 def attributes(self):
506 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.
510 >>> attr = entity.attribute_set.get(key='spam')
511 DoesNotExist: Attribute matching query does not exist.
512 >>> attr = entity.parent.attribute_set.get(key='spam')
515 >>> entity.attributes['spam']
521 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
522 return super(TreeEntity, self).attributes