Moved docs for MultiViews and the concrete View subclasses from rst to source.
[philo.git] / philo / models / base.py
1 from UserDict import DictMixin
2
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
12
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
18
19
20 class Tag(models.Model):
21         name = models.CharField(max_length=255)
22         slug = models.SlugField(max_length=255, unique=True)
23         
24         def __unicode__(self):
25                 return self.name
26         
27         class Meta:
28                 app_label = 'philo'
29                 ordering = ('name',)
30
31
32 class Titled(models.Model):
33         title = models.CharField(max_length=255)
34         slug = models.SlugField(max_length=255)
35         
36         def __unicode__(self):
37                 return self.title
38         
39         class Meta:
40                 abstract = True
41
42
43 #: 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.
44 value_content_type_limiter = ContentTypeRegistryLimiter()
45
46
47 def register_value_model(model):
48         """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
49         value_content_type_limiter.register_class(model)
50
51
52 register_value_model(Tag)
53
54
55 def unregister_value_model(model):
56         """Registers a model as a valid content type for a :class:`ForeignKeyValue` or :class:`ManyToManyValue` through the :data:`value_content_type_limiter`."""
57         value_content_type_limiter.unregister_class(model)
58
59
60 class AttributeValue(models.Model):
61         """
62         This is an abstract base class for models that can be used as values for :class:`Attribute`\ s.
63         
64         AttributeValue subclasses are expected to supply access to a clean version of their value through an attribute called "value".
65         
66         """
67         
68         #: :class:`GenericRelation` to :class:`Attribute`
69         attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
70         
71         def set_value(self, value):
72                 """Given a ``value``, sets the appropriate fields so that it can be correctly stored in the database."""
73                 raise NotImplementedError
74         
75         def value_formfields(self, **kwargs):
76                 """
77                 Returns any formfields that would be used to construct an instance of this value.
78                 
79                 :returns: A dictionary mapping field names to formfields.
80                 
81                 """
82                 
83                 raise NotImplementedError
84         
85         def construct_instance(self, **kwargs):
86                 """Applies cleaned data from the formfields generated by valid_formfields to oneself."""
87                 raise NotImplementedError
88         
89         def __unicode__(self):
90                 return unicode(self.value)
91         
92         class Meta:
93                 abstract = True
94
95
96 #: An instance of :class:`ContentTypeSubclassLimiter` which is used to track the content types which are considered valid value models for an :class:`Attribute`.
97 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
98
99
100 class JSONValue(AttributeValue):
101         """Stores a python object as a json string."""
102         value = JSONField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.', default='null', db_index=True)
103         
104         def __unicode__(self):
105                 return force_unicode(self.value)
106         
107         def value_formfields(self):
108                 kwargs = {'initial': self.value_json}
109                 field = self._meta.get_field('value')
110                 return {field.name: field.formfield(**kwargs)}
111         
112         def construct_instance(self, **kwargs):
113                 field_name = self._meta.get_field('value').name
114                 self.set_value(kwargs.pop(field_name, None))
115         
116         def set_value(self, value):
117                 self.value = value
118         
119         class Meta:
120                 app_label = 'philo'
121
122
123 class ForeignKeyValue(AttributeValue):
124         """Stores a generic relationship to an instance of any value content type (as defined by the :data:`value_content_type_limiter`)."""
125         content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
126         object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
127         value = generic.GenericForeignKey()
128         
129         def value_formfields(self):
130                 field = self._meta.get_field('content_type')
131                 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
132                 
133                 if self.content_type:
134                         kwargs = {
135                                 'initial': self.object_id,
136                                 'required': False,
137                                 'queryset': self.content_type.model_class()._default_manager.all()
138                         }
139                         fields['value'] = forms.ModelChoiceField(**kwargs)
140                 return fields
141         
142         def construct_instance(self, **kwargs):
143                 field_name = self._meta.get_field('content_type').name
144                 ct = kwargs.pop(field_name, None)
145                 if ct is None or ct != self.content_type:
146                         self.object_id = None
147                         self.content_type = ct
148                 else:
149                         value = kwargs.pop('value', None)
150                         self.set_value(value)
151                         if value is None:
152                                 self.content_type = ct
153         
154         def set_value(self, value):
155                 self.value = value
156         
157         class Meta:
158                 app_label = 'philo'
159
160
161 class ManyToManyValue(AttributeValue):
162         """Stores a generic relationship to many instances of any value content type (as defined by the :data:`value_content_type_limiter`)."""
163         content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
164         values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
165         
166         def get_object_ids(self):
167                 return self.values.values_list('object_id', flat=True)
168         object_ids = property(get_object_ids)
169         
170         def set_value(self, value):
171                 # Value must be a queryset. Watch out for ModelMultipleChoiceField;
172                 # it returns its value as a list if empty.
173                 
174                 self.content_type = ContentType.objects.get_for_model(value.model)
175                 
176                 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
177                 # a pk.
178                 if self.pk is None:
179                         self.save()
180                 
181                 object_ids = value.values_list('id', flat=True)
182                 
183                 # These lines shouldn't be necessary; however, if object_ids is an EmptyQuerySet,
184                 # the code (specifically the object_id__in query) won't work without them. Unclear why...
185                 # TODO: is this still the case?
186                 if not object_ids:
187                         self.values.all().delete()
188                 else:
189                         self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
190                         
191                         current_ids = self.object_ids
192                         
193                         for object_id in object_ids:
194                                 if object_id in current_ids:
195                                         continue
196                                 self.values.create(content_type=self.content_type, object_id=object_id)
197         
198         def get_value(self):
199                 if self.content_type is None:
200                         return None
201                 
202                 # HACK to be safely explicit until http://code.djangoproject.com/ticket/15145 is resolved
203                 object_ids = self.object_ids
204                 manager = self.content_type.model_class()._default_manager
205                 if not object_ids:
206                         return manager.none()
207                 return manager.filter(id__in=self.object_ids)
208         
209         value = property(get_value, set_value)
210         
211         def value_formfields(self):
212                 field = self._meta.get_field('content_type')
213                 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
214                 
215                 if self.content_type:
216                         kwargs = {
217                                 'initial': self.object_ids,
218                                 'required': False,
219                                 'queryset': self.content_type.model_class()._default_manager.all()
220                         }
221                         fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
222                 return fields
223         
224         def construct_instance(self, **kwargs):
225                 field_name = self._meta.get_field('content_type').name
226                 ct = kwargs.pop(field_name, None)
227                 if ct is None or ct != self.content_type:
228                         self.values.clear()
229                         self.content_type = ct
230                 else:
231                         value = kwargs.get('value', None)
232                         if not value:
233                                 value = self.content_type.model_class()._default_manager.none()
234                         self.set_value(value)
235         construct_instance.alters_data = True
236         
237         class Meta:
238                 app_label = 'philo'
239
240
241 class Attribute(models.Model):
242         """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`."""
243         entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
244         entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID', db_index=True)
245         
246         #: :class:`GenericForeignKey` to anything (generally an instance of an Entity subclass).
247         entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
248         
249         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)
250         value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True, db_index=True)
251         
252         #: :class:`GenericForeignKey` to an instance of a subclass of :class:`AttributeValue` as determined by the :data:`attribute_value_limiter`.
253         value = generic.GenericForeignKey('value_content_type', 'value_object_id')
254         
255         #: :class:`CharField` containing a key (up to 255 characters) consisting of alphanumeric characters and underscores.
256         key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.", db_index=True)
257         
258         def __unicode__(self):
259                 return u'"%s": %s' % (self.key, self.value)
260         
261         class Meta:
262                 app_label = 'philo'
263                 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
264
265
266 class QuerySetMapper(object, DictMixin):
267         def __init__(self, queryset, passthrough=None):
268                 self.queryset = queryset
269                 self.passthrough = passthrough
270         
271         def __getitem__(self, key):
272                 try:
273                         value = self.queryset.get(key__exact=key).value
274                 except ObjectDoesNotExist:
275                         if self.passthrough is not None:
276                                 return self.passthrough.__getitem__(key)
277                         raise KeyError
278                 else:
279                         if value is not None:
280                                 return value.value
281                         return value
282         
283         def keys(self):
284                 keys = set(self.queryset.values_list('key', flat=True).distinct())
285                 if self.passthrough is not None:
286                         keys |= set(self.passthrough.keys())
287                 return list(keys)
288
289
290 class EntityOptions(object):
291         def __init__(self, options):
292                 if options is not None:
293                         for key, value in options.__dict__.items():
294                                 setattr(self, key, value)
295                 if not hasattr(self, 'proxy_fields'):
296                         self.proxy_fields = []
297         
298         def add_proxy_field(self, proxy_field):
299                 self.proxy_fields.append(proxy_field)
300
301
302 class EntityBase(models.base.ModelBase):
303         def __new__(cls, name, bases, attrs):
304                 entity_meta = attrs.pop('EntityMeta', None)
305                 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
306                 new.add_to_class('_entity_meta', EntityOptions(entity_meta))
307                 entity_class_prepared.send(sender=new)
308                 return new
309
310
311 class Entity(models.Model):
312         """An abstract class that simplifies access to related attributes. Most models provided by Philo subclass Entity."""
313         __metaclass__ = EntityBase
314         
315         attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
316         
317         @property
318         def attributes(self):
319                 """
320                 Property that returns a dictionary-like object which can be used to retrieve related :class:`Attribute`\ s' values directly.
321
322                 Example::
323
324                         >>> attr = entity.attribute_set.get(key='spam')
325                         >>> attr.value.value
326                         u'eggs'
327                         >>> entity.attributes['spam']
328                         u'eggs'
329                 
330                 """
331                 
332                 return QuerySetMapper(self.attribute_set.all())
333         
334         class Meta:
335                 abstract = True
336
337
338 class TreeManager(models.Manager):
339         use_for_related_fields = True
340         
341         def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
342                 """
343                 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).
344                 
345                 .. 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.
346                 
347                 .. 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.
348                 
349                 :param path: The path of the object
350                 :param root: The object which will be considered the root of the search
351                 :param absolute_result: Whether to return an absolute result or do a binary search
352                 :param pathsep: The path separator used in ``path``
353                 :param field: The field on the model which should be queried for ``path`` segment matching.
354                 :returns: An instance if absolute_result is True or (instance, remaining_path) otherwise.
355                 
356                 """
357                 
358                 segments = path.split(pathsep)
359                 
360                 # Clean out blank segments. Handles multiple consecutive pathseps.
361                 while True:
362                         try:
363                                 segments.remove('')
364                         except ValueError:
365                                 break
366                 
367                 # Special-case a lack of segments. No queries necessary.
368                 if not segments:
369                         if root is not None:
370                                 if absolute_result:
371                                         return root
372                                 return root, None
373                         else:
374                                 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
375                 
376                 def make_query_kwargs(segments, root):
377                         kwargs = {}
378                         prefix = ""
379                         revsegs = list(segments)
380                         revsegs.reverse()
381                         
382                         for segment in revsegs:
383                                 kwargs["%s%s__exact" % (prefix, field)] = segment
384                                 prefix += "parent__"
385                         
386                         if prefix:
387                                 kwargs[prefix[:-2]] = root
388                         
389                         return kwargs
390                 
391                 def find_obj(segments, depth, deepest_found=None):
392                         if deepest_found is None:
393                                 deepest_level = 0
394                         elif root is None:
395                                 deepest_level = deepest_found.get_level() + 1
396                         else:
397                                 deepest_level = deepest_found.get_level() - root.get_level()
398                         try:
399                                 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
400                         except self.model.DoesNotExist:
401                                 if not deepest_level and depth > 1:
402                                         # make sure there's a root node...
403                                         depth = 1
404                                 else:
405                                         # Try finding one with half the path since the deepest find.
406                                         depth = (deepest_level + depth)/2
407                                 
408                                 if deepest_level == depth:
409                                         # This should happen if nothing is found with any part of the given path.
410                                         if root is not None and deepest_found is None:
411                                                 return root, pathsep.join(segments)
412                                         raise
413                                 
414                                 return find_obj(segments, depth, deepest_found)
415                         else:
416                                 # Yay! Found one!
417                                 if root is None:
418                                         deepest_level = obj.get_level() + 1
419                                 else:
420                                         deepest_level = obj.get_level() - root.get_level()
421                                 
422                                 # Could there be a deeper one?
423                                 if obj.is_leaf_node():
424                                         return obj, pathsep.join(segments[deepest_level:]) or None
425                                 
426                                 depth += (len(segments) - depth)/2 or len(segments) - depth
427                                 
428                                 if depth > deepest_level + obj.get_descendant_count():
429                                         depth = deepest_level + obj.get_descendant_count()
430                                 
431                                 if deepest_level == depth:
432                                         return obj, pathsep.join(segments[deepest_level:]) or None
433                                 
434                                 try:
435                                         return find_obj(segments, depth, obj)
436                                 except self.model.DoesNotExist:
437                                         # Then this was the deepest.
438                                         return obj, pathsep.join(segments[deepest_level:])
439                 
440                 if absolute_result:
441                         return self.get(**make_query_kwargs(segments, root))
442                 
443                 # Try a modified binary search algorithm. Feed the root in so that query complexity
444                 # can be reduced. It might be possible to weight the search towards the beginning
445                 # of the path, since short paths are more likely, but how far forward? It would
446                 # need to shift depending on len(segments) - perhaps logarithmically?
447                 return find_obj(segments, len(segments)/2 or len(segments))
448
449
450 class TreeModel(MPTTModel):
451         objects = TreeManager()
452         parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
453         slug = models.SlugField(max_length=255)
454         
455         def get_path(self, root=None, pathsep='/', field='slug'):
456                 """
457                 :param root: Only return the path since this object.
458                 :param pathsep: The path separator to use when constructing an instance's path
459                 :param field: The field to pull path information from for each ancestor.
460                 :returns: A string representation of an object's path.
461                 
462                 """
463                 
464                 if root == self:
465                         return ''
466                 
467                 if root is not None and not self.is_descendant_of(root):
468                         raise AncestorDoesNotExist(root)
469                 
470                 qs = self.get_ancestors(include_self=True)
471                 
472                 if root is not None:
473                         qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
474                 
475                 return pathsep.join([getattr(parent, field, '?') for parent in qs])
476         path = property(get_path)
477         
478         def __unicode__(self):
479                 return self.path
480         
481         class Meta:
482                 unique_together = (('parent', 'slug'),)
483                 abstract = True
484
485
486 class TreeEntityBase(MPTTModelBase, EntityBase):
487         def __new__(meta, name, bases, attrs):
488                 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
489                 cls = EntityBase.__new__(meta, name, bases, attrs)
490                 
491                 return meta.register(cls)
492
493
494 class TreeEntity(Entity, TreeModel):
495         """An abstract subclass of Entity which represents a tree relationship."""
496         
497         __metaclass__ = TreeEntityBase
498         
499         @property
500         def attributes(self):
501                 """
502                 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.
503
504                 Example::
505
506                         >>> attr = entity.attribute_set.get(key='spam')
507                         DoesNotExist: Attribute matching query does not exist.
508                         >>> attr = entity.parent.attribute_set.get(key='spam')
509                         >>> attr.value.value
510                         u'eggs'
511                         >>> entity.attributes['spam']
512                         u'eggs'
513                 
514                 """
515                 
516                 if self.parent:
517                         return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
518                 return super(TreeEntity, self).attributes
519         
520         class Meta:
521                 abstract = True