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.core.validators import RegexValidator
7 from django.utils import simplejson as json
8 from django.utils.encoding import force_unicode
9 from philo.exceptions import AncestorDoesNotExist
10 from philo.models.fields import JSONField
11 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
12 from philo.signals import entity_class_prepared
13 from philo.validators import json_validator
14 from UserDict import DictMixin
15 from mptt.models import MPTTModel, MPTTModelBase, MPTTOptions
18 class Tag(models.Model):
19 name = models.CharField(max_length=255)
20 slug = models.SlugField(max_length=255, unique=True)
22 def __unicode__(self):
30 class Titled(models.Model):
31 title = models.CharField(max_length=255)
32 slug = models.SlugField(max_length=255)
34 def __unicode__(self):
41 #: An instance of :class:`ContentTypeRegistryLimiter` which is used to track the content types which can be related to by ForeignKeyValues and ManyToManyValues.
42 value_content_type_limiter = ContentTypeRegistryLimiter()
45 def register_value_model(model):
46 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
47 value_content_type_limiter.register_class(model)
50 register_value_model(Tag)
53 def unregister_value_model(model):
54 """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
55 value_content_type_limiter.unregister_class(model)
58 class AttributeValue(models.Model):
60 This is an abstract base class for models that can be used as values for :class:`Attribute`\ s.
62 AttributeValue subclasses are expected to supply access to a clean version of their value through an attribute called "value".
66 #: :class:`GenericRelation` to :class:`Attribute`
67 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
69 def set_value(self, value):
70 """Given a ``value``, sets the appropriate fields so that it can be correctly stored in the database."""
71 raise NotImplementedError
73 def value_formfields(self, **kwargs):
75 Returns any formfields that would be used to construct an instance of this value.
77 :returns: A dictionary mapping field names to formfields.
81 raise NotImplementedError
83 def construct_instance(self, **kwargs):
84 """Applies cleaned data from the formfields generated by valid_formfields to oneself."""
85 raise NotImplementedError
87 def __unicode__(self):
88 return unicode(self.value)
94 #: An instance of :class:`ContentTypeSubclassLimiter` which is used to track the content types which are considered valid value models for an :class:`Attribute`.
95 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
98 class JSONValue(AttributeValue):
99 """Stores a python object as a json string."""
100 value = JSONField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.', default='null', db_index=True)
102 def __unicode__(self):
103 return force_unicode(self.value)
105 def value_formfields(self):
106 kwargs = {'initial': self.value_json}
107 field = self._meta.get_field('value')
108 return {field.name: field.formfield(**kwargs)}
110 def construct_instance(self, **kwargs):
111 field_name = self._meta.get_field('value').name
112 self.set_value(kwargs.pop(field_name, None))
114 def set_value(self, value):
121 class ForeignKeyValue(AttributeValue):
122 """Stores a generic relationship to an instance of any value content type (as defined by the :data:`value_content_type_limiter`)."""
123 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
124 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
125 value = generic.GenericForeignKey()
127 def value_formfields(self):
128 field = self._meta.get_field('content_type')
129 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
131 if self.content_type:
133 'initial': self.object_id,
135 'queryset': self.content_type.model_class()._default_manager.all()
137 fields['value'] = forms.ModelChoiceField(**kwargs)
140 def construct_instance(self, **kwargs):
141 field_name = self._meta.get_field('content_type').name
142 ct = kwargs.pop(field_name, None)
143 if ct is None or ct != self.content_type:
144 self.object_id = None
145 self.content_type = ct
147 value = kwargs.pop('value', None)
148 self.set_value(value)
150 self.content_type = ct
152 def set_value(self, value):
159 class ManyToManyValue(AttributeValue):
160 """Stores a generic relationship to many instances of any value content type (as defined by the :data:`value_content_type_limiter`)."""
161 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
162 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
164 def get_object_ids(self):
165 return self.values.values_list('object_id', flat=True)
166 object_ids = property(get_object_ids)
168 def set_value(self, value):
169 # Value must be a queryset. Watch out for ModelMultipleChoiceField;
170 # it returns its value as a list if empty.
172 self.content_type = ContentType.objects.get_for_model(value.model)
174 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
179 object_ids = value.values_list('id', flat=True)
181 # These lines shouldn't be necessary; however, if object_ids is an EmptyQuerySet,
182 # the code (specifically the object_id__in query) won't work without them. Unclear why...
183 # TODO: is this still the case?
185 self.values.all().delete()
187 self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
189 current_ids = self.object_ids
191 for object_id in object_ids:
192 if object_id in current_ids:
194 self.values.create(content_type=self.content_type, object_id=object_id)
197 if self.content_type is None:
200 # HACK to be safely explicit until http://code.djangoproject.com/ticket/15145 is resolved
201 object_ids = self.object_ids
202 manager = self.content_type.model_class()._default_manager
204 return manager.none()
205 return manager.filter(id__in=self.object_ids)
207 value = property(get_value, set_value)
209 def value_formfields(self):
210 field = self._meta.get_field('content_type')
211 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
213 if self.content_type:
215 'initial': self.object_ids,
217 'queryset': self.content_type.model_class()._default_manager.all()
219 fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
222 def construct_instance(self, **kwargs):
223 field_name = self._meta.get_field('content_type').name
224 ct = kwargs.pop(field_name, None)
225 if ct is None or ct != self.content_type:
227 self.content_type = ct
229 value = kwargs.get('value', None)
231 value = self.content_type.model_class()._default_manager.none()
232 self.set_value(value)
233 construct_instance.alters_data = True
239 class Attribute(models.Model):
240 """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`."""
241 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
242 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID', db_index=True)
244 #: :class:`GenericForeignKey` to anything (generally an instance of an Entity subclass).
245 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
247 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)
248 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
250 #: :class:`GenericForeignKey` to an instance of a subclass of :class:`AttributeValue` as determined by the :data:`attribute_value_limiter`.
251 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
253 #: :class:`CharField` containing a key (up to 255 characters) consisting of alphanumeric characters and underscores.
254 key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
256 def __unicode__(self):
257 return u'"%s": %s' % (self.key, self.value)
261 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
264 class QuerySetMapper(object, DictMixin):
265 def __init__(self, queryset, passthrough=None):
266 self.queryset = queryset
267 self.passthrough = passthrough
269 def __getitem__(self, key):
271 value = self.queryset.get(key__exact=key).value
272 except ObjectDoesNotExist:
273 if self.passthrough is not None:
274 return self.passthrough.__getitem__(key)
277 if value is not None:
282 keys = set(self.queryset.values_list('key', flat=True).distinct())
283 if self.passthrough is not None:
284 keys |= set(self.passthrough.keys())
288 class EntityOptions(object):
289 def __init__(self, options):
290 if options is not None:
291 for key, value in options.__dict__.items():
292 setattr(self, key, value)
293 if not hasattr(self, 'proxy_fields'):
294 self.proxy_fields = []
296 def add_proxy_field(self, proxy_field):
297 self.proxy_fields.append(proxy_field)
300 class EntityBase(models.base.ModelBase):
301 def __new__(cls, name, bases, attrs):
302 entity_meta = attrs.pop('EntityMeta', None)
303 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
304 new.add_to_class('_entity_meta', EntityOptions(entity_meta))
305 entity_class_prepared.send(sender=new)
309 class Entity(models.Model):
310 """An abstract class that simplifies access to related attributes. Most models provided by Philo subclass Entity."""
311 __metaclass__ = EntityBase
313 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
316 def attributes(self):
318 Property that returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
322 >>> attr = entity.attribute_set.get(key='spam')
325 >>> entity.attributes['spam']
330 return QuerySetMapper(self.attribute_set.all())
336 class TreeManager(models.Manager):
337 use_for_related_fields = True
339 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
341 If ``absolute_result`` is ``True``, returns the object at ``path`` (starting at ``root``) or raises a :exception:`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).
343 .. 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.
345 .. 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.
347 :param path: The path of the object
348 :param root: The object which will be considered the root of the search
349 :param absolute_result: Whether to return an absolute result or do a binary search
350 :param pathsep: The path separator used in ``path``
351 :param field: The field on the model which should be queried for ``path`` segment matching.
352 :returns: An instance if absolute_result is True or (instance, remaining_path) otherwise.
356 segments = path.split(pathsep)
358 # Clean out blank segments. Handles multiple consecutive pathseps.
365 # Special-case a lack of segments. No queries necessary.
372 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
374 def make_query_kwargs(segments, root):
377 revsegs = list(segments)
380 for segment in revsegs:
381 kwargs["%s%s__exact" % (prefix, field)] = segment
385 kwargs[prefix[:-2]] = root
389 def find_obj(segments, depth, deepest_found=None):
390 if deepest_found is None:
393 deepest_level = deepest_found.get_level() + 1
395 deepest_level = deepest_found.get_level() - root.get_level()
397 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
398 except self.model.DoesNotExist:
399 if not deepest_level and depth > 1:
400 # make sure there's a root node...
403 # Try finding one with half the path since the deepest find.
404 depth = (deepest_level + depth)/2
406 if deepest_level == depth:
407 # This should happen if nothing is found with any part of the given path.
408 if root is not None and deepest_found is None:
409 return root, pathsep.join(segments)
412 return find_obj(segments, depth, deepest_found)
416 deepest_level = obj.get_level() + 1
418 deepest_level = obj.get_level() - root.get_level()
420 # Could there be a deeper one?
421 if obj.is_leaf_node():
422 return obj, pathsep.join(segments[deepest_level:]) or None
424 depth += (len(segments) - depth)/2 or len(segments) - depth
426 if depth > deepest_level + obj.get_descendant_count():
427 depth = deepest_level + obj.get_descendant_count()
429 if deepest_level == depth:
430 return obj, pathsep.join(segments[deepest_level:]) or None
433 return find_obj(segments, depth, obj)
434 except self.model.DoesNotExist:
435 # Then this was the deepest.
436 return obj, pathsep.join(segments[deepest_level:])
439 return self.get(**make_query_kwargs(segments, root))
441 # Try a modified binary search algorithm. Feed the root in so that query complexity
442 # can be reduced. It might be possible to weight the search towards the beginning
443 # of the path, since short paths are more likely, but how far forward? It would
444 # need to shift depending on len(segments) - perhaps logarithmically?
445 return find_obj(segments, len(segments)/2 or len(segments))
448 class TreeModel(MPTTModel):
449 objects = TreeManager()
450 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
451 slug = models.SlugField(max_length=255)
453 def get_path(self, root=None, pathsep='/', field='slug'):
455 :param root: Only return the path since this object.
456 :param pathsep: The path separator to use when constructing an instance's path
457 :param field: The field to pull path information from for each ancestor.
458 :returns: A string representation of an object's path.
465 if root is not None and not self.is_descendant_of(root):
466 raise AncestorDoesNotExist(root)
468 qs = self.get_ancestors(include_self=True)
471 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
473 return pathsep.join([getattr(parent, field, '?') for parent in qs])
474 path = property(get_path)
476 def __unicode__(self):
480 unique_together = (('parent', 'slug'),)
484 class TreeEntityBase(MPTTModelBase, EntityBase):
485 def __new__(meta, name, bases, attrs):
486 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
487 cls = EntityBase.__new__(meta, name, bases, attrs)
489 return meta.register(cls)
492 class TreeEntity(Entity, TreeModel):
493 """An abstract subclass of Entity which represents a tree relationship."""
495 __metaclass__ = TreeEntityBase
498 def attributes(self):
500 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.
504 >>> attr = entity.attribute_set.get(key='spam')
505 DoesNotExist: Attribute matching query does not exist.
506 >>> attr = entity.parent.attribute_set.get(key='spam')
509 >>> entity.attributes['spam']
515 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
516 return super(TreeEntity, self).attributes