Split utils into entities (i.e. AttributeMappers) and other utils. Added documentatio...
[philo.git] / philo / models / base.py
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
10
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
17
18
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)
25         
26         def __unicode__(self):
27                 """Returns the value of the :attr:`name` field"""
28                 return self.name
29         
30         class Meta:
31                 app_label = 'philo'
32                 ordering = ('name',)
33
34
35 class Titled(models.Model):
36         title = models.CharField(max_length=255)
37         slug = models.SlugField(max_length=255)
38         
39         def __unicode__(self):
40                 return self.title
41         
42         class Meta:
43                 abstract = True
44
45
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()
48
49
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)
53
54
55 register_value_model(Tag)
56
57
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)
61
62
63 class AttributeValue(models.Model):
64         """
65         This is an abstract base class for models that can be used as values for :class:`Attribute`\ s.
66         
67         AttributeValue subclasses are expected to supply access to a clean version of their value through an attribute called "value".
68         
69         """
70         
71         #: :class:`GenericRelation` to :class:`Attribute`
72         attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
73         
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
77         
78         def value_formfields(self, **kwargs):
79                 """
80                 Returns any formfields that would be used to construct an instance of this value.
81                 
82                 :returns: A dictionary mapping field names to formfields.
83                 
84                 """
85                 
86                 raise NotImplementedError
87         
88         def construct_instance(self, **kwargs):
89                 """Applies cleaned data from the formfields generated by valid_formfields to oneself."""
90                 raise NotImplementedError
91         
92         def __unicode__(self):
93                 return unicode(self.value)
94         
95         class Meta:
96                 abstract = True
97
98
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)
101
102
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)
106         
107         def __unicode__(self):
108                 return force_unicode(self.value)
109         
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)}
114         
115         def construct_instance(self, **kwargs):
116                 field_name = self._meta.get_field('value').name
117                 self.set_value(kwargs.pop(field_name, None))
118         
119         def set_value(self, value):
120                 self.value = value
121         
122         class Meta:
123                 app_label = 'philo'
124
125
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()
131         
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))}
135                 
136                 if self.content_type:
137                         kwargs = {
138                                 'initial': self.object_id,
139                                 'required': False,
140                                 'queryset': self.content_type.model_class()._default_manager.all()
141                         }
142                         fields['value'] = forms.ModelChoiceField(**kwargs)
143                 return fields
144         
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
151                 else:
152                         value = kwargs.pop('value', None)
153                         self.set_value(value)
154                         if value is None:
155                                 self.content_type = ct
156         
157         def set_value(self, value):
158                 self.value = value
159         
160         class Meta:
161                 app_label = 'philo'
162
163
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)
168         
169         def get_object_ids(self):
170                 return self.values.values_list('object_id', flat=True)
171         object_ids = property(get_object_ids)
172         
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.
176                 
177                 self.content_type = ContentType.objects.get_for_model(value.model)
178                 
179                 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
180                 # a pk.
181                 if self.pk is None:
182                         self.save()
183                 
184                 object_ids = value.values_list('id', flat=True)
185                 
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?
189                 if not object_ids:
190                         self.values.all().delete()
191                 else:
192                         self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
193                         
194                         current_ids = self.object_ids
195                         
196                         for object_id in object_ids:
197                                 if object_id in current_ids:
198                                         continue
199                                 self.values.create(content_type=self.content_type, object_id=object_id)
200         
201         def get_value(self):
202                 if self.content_type is None:
203                         return None
204                 
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
208                 if not object_ids:
209                         return manager.none()
210                 return manager.filter(id__in=self.object_ids)
211         
212         value = property(get_value, set_value)
213         
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))}
217                 
218                 if self.content_type:
219                         kwargs = {
220                                 'initial': self.object_ids,
221                                 'required': False,
222                                 'queryset': self.content_type.model_class()._default_manager.all()
223                         }
224                         fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
225                 return fields
226         
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:
231                         self.values.clear()
232                         self.content_type = ct
233                 else:
234                         value = kwargs.get('value', None)
235                         if not value:
236                                 value = self.content_type.model_class()._default_manager.none()
237                         self.set_value(value)
238         construct_instance.alters_data = True
239         
240         class Meta:
241                 app_label = 'philo'
242
243
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)
248         
249         #: :class:`GenericForeignKey` to anything (generally an instance of an Entity subclass).
250         entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
251         
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)
254         
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')
257         
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)
260         
261         def __unicode__(self):
262                 return u'"%s": %s' % (self.key, self.value)
263         
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):
267                         val = self.value
268                 else:
269                         if isinstance(self.value, models.Model):
270                                 self.value.delete()
271                         val = value_class()
272                 
273                 val.set_value(value)
274                 val.save()
275                 
276                 self.value = val
277                 self.save()
278         
279         class Meta:
280                 app_label = 'philo'
281                 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
282
283
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 = []
291         
292         def add_proxy_field(self, proxy_field):
293                 self.proxy_fields.append(proxy_field)
294
295
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)
302                 return new
303
304
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
308         
309         attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
310         
311         def get_attribute_mapper(self, mapper=AttributeMapper):
312                 """
313                 Returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
314
315                 Example::
316
317                         >>> attr = entity.attribute_set.get(key='spam')
318                         >>> attr.value.value
319                         u'eggs'
320                         >>> entity.attributes['spam']
321                         u'eggs'
322                 
323                 """
324                 return mapper(self)
325         attributes = property(get_attribute_mapper)
326         
327         class Meta:
328                 abstract = True
329
330
331 class TreeManager(models.Manager):
332         use_for_related_fields = True
333         
334         def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
335                 """
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).
337                 
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.
339                 
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.
341                 
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.
349                 
350                 """
351                 
352                 segments = path.split(pathsep)
353                 
354                 # Clean out blank segments. Handles multiple consecutive pathseps.
355                 while True:
356                         try:
357                                 segments.remove('')
358                         except ValueError:
359                                 break
360                 
361                 # Special-case a lack of segments. No queries necessary.
362                 if not segments:
363                         if root is not None:
364                                 if absolute_result:
365                                         return root
366                                 return root, None
367                         else:
368                                 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
369                 
370                 def make_query_kwargs(segments, root):
371                         kwargs = {}
372                         prefix = ""
373                         revsegs = list(segments)
374                         revsegs.reverse()
375                         
376                         for segment in revsegs:
377                                 kwargs["%s%s__exact" % (prefix, field)] = segment
378                                 prefix += "parent__"
379                         
380                         if prefix:
381                                 kwargs[prefix[:-2]] = root
382                         
383                         return kwargs
384                 
385                 def find_obj(segments, depth, deepest_found=None):
386                         if deepest_found is None:
387                                 deepest_level = 0
388                         elif root is None:
389                                 deepest_level = deepest_found.get_level() + 1
390                         else:
391                                 deepest_level = deepest_found.get_level() - root.get_level()
392                         try:
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...
397                                         depth = 1
398                                 else:
399                                         # Try finding one with half the path since the deepest find.
400                                         depth = (deepest_level + depth)/2
401                                 
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)
406                                         raise
407                                 
408                                 return find_obj(segments, depth, deepest_found)
409                         else:
410                                 # Yay! Found one!
411                                 if root is None:
412                                         deepest_level = obj.get_level() + 1
413                                 else:
414                                         deepest_level = obj.get_level() - root.get_level()
415                                 
416                                 # Could there be a deeper one?
417                                 if obj.is_leaf_node():
418                                         return obj, pathsep.join(segments[deepest_level:]) or None
419                                 
420                                 depth += (len(segments) - depth)/2 or len(segments) - depth
421                                 
422                                 if depth > deepest_level + obj.get_descendant_count():
423                                         depth = deepest_level + obj.get_descendant_count()
424                                 
425                                 if deepest_level == depth:
426                                         return obj, pathsep.join(segments[deepest_level:]) or None
427                                 
428                                 try:
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:])
433                 
434                 if absolute_result:
435                         return self.get(**make_query_kwargs(segments, root))
436                 
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))
442
443
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)
448         
449         def get_path(self, root=None, pathsep='/', field='slug'):
450                 """
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.
455                 
456                 """
457                 
458                 if root == self:
459                         return ''
460                 
461                 if root is not None and not self.is_descendant_of(root):
462                         raise AncestorDoesNotExist(root)
463                 
464                 qs = self.get_ancestors(include_self=True)
465                 
466                 if root is not None:
467                         qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
468                 
469                 return pathsep.join([getattr(parent, field, '?') for parent in qs])
470         path = property(get_path)
471         
472         def __unicode__(self):
473                 return self.path
474         
475         class Meta:
476                 unique_together = (('parent', 'slug'),)
477                 abstract = True
478
479
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)
484                 
485                 return meta.register(cls)
486
487
488 class TreeEntity(Entity, TreeModel):
489         """An abstract subclass of Entity which represents a tree relationship."""
490         
491         __metaclass__ = TreeEntityBase
492         
493         def get_attribute_mapper(self, mapper=None):
494                 """
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.
496
497                 Example::
498
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')
502                         >>> attr.value.value
503                         u'eggs'
504                         >>> entity.attributes['spam']
505                         u'eggs'
506                 
507                 """
508                 if mapper is None:
509                         if self.parent:
510                                 mapper = TreeAttributeMapper
511                         else:
512                                 mapper = AttributeMapper
513                 return super(TreeEntity, self).get_attribute_mapper(mapper)
514         attributes = property(get_attribute_mapper)
515         
516         class Meta:
517                 abstract = True