Reduced number of queries for BlogView.get_entries_by_tag. Corrected waldo's AccountM...
[philo.git] / models / base.py
index c2c12ad..8140520 100644 (file)
@@ -2,8 +2,10 @@ from django import forms
 from django.db import models
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes import generic
-from django.utils import simplejson as json
 from django.core.exceptions import ObjectDoesNotExist
+from django.core.validators import RegexValidator
+from django.utils import simplejson as json
+from django.utils.encoding import smart_str
 from philo.exceptions import AncestorDoesNotExist
 from philo.models.fields import JSONField
 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
@@ -22,6 +24,7 @@ class Tag(models.Model):
        
        class Meta:
                app_label = 'philo'
+               ordering = ('name',)
 
 
 class Titled(models.Model):
@@ -73,7 +76,7 @@ class JSONValue(AttributeValue):
        value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
        
        def __unicode__(self):
-               return self.value_json
+               return smart_str(self.value)
        
        def value_formfield(self, **kwargs):
                kwargs['initial'] = self.value_json
@@ -178,7 +181,7 @@ class Attribute(models.Model):
        value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
        value = generic.GenericForeignKey('value_content_type', 'value_object_id')
        
-       key = models.CharField(max_length=255)
+       key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.")
        
        def __unicode__(self):
                return u'"%s": %s' % (self.key, self.value)
@@ -282,10 +285,14 @@ class TreeManager(models.Manager):
        
        def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
                """
-               Given a <pathsep>-separated path, fetch the matching model of this type. If the path
-               you're searching for is known to exist, it is always faster to use absolute_result=True.
-               Unless the path depth is over ~40, in which case the high cost of the absolute query
-               makes a binary search (i.e. non-absolute) faster.
+               Returns the object with the path, unless absolute_result is set to False, in which
+               case it returns a tuple containing the deepest object found along the path, and the
+               remainder of the path after that object as a string (or None if there is no remaining
+               path). Raises a DoesNotExist exception if no object is found with the given path.
+               
+               If the path you're searching for is known to exist, it is always faster to use
+               absolute_result=True - unless the path depth is over ~40, in which case the high cost
+               of the absolute query makes a binary search (i.e. non-absolute) faster.
                """
                # 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
@@ -324,9 +331,6 @@ class TreeManager(models.Manager):
                                kwargs["%s%s__exact" % (prefix, field)] = segment
                                prefix += "parent__"
                        
-                       if not prefix and root is not None:
-                               prefix = "parent__"
-                       
                        if prefix:
                                kwargs[prefix[:-2]] = root
                        
@@ -338,13 +342,15 @@ class TreeManager(models.Manager):
                                path += pathsep
                        return path
                
-               def find_obj(segments, depth, deepest_found):
+               def find_obj(segments, depth, deepest_found=None):
                        if deepest_found is None:
                                deepest_level = 0
-                       else:
+                       elif root is None:
                                deepest_level = deepest_found.get_level() + 1
+                       else:
+                               deepest_level = deepest_found.get_level() - root.get_level()
                        try:
-                               obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found))
+                               obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
                        except self.model.DoesNotExist:
                                if not deepest_level and depth > 1:
                                        # make sure there's a root node...
@@ -355,12 +361,17 @@ class TreeManager(models.Manager):
                                
                                if deepest_level == depth:
                                        # This should happen if nothing is found with any part of the given path.
+                                       if root is not None and deepest_found is None:
+                                               return root, build_path(segments)
                                        raise
                                
                                return find_obj(segments, depth, deepest_found)
                        else:
                                # Yay! Found one!
-                               deepest_level = obj.get_level() + 1
+                               if root is None:
+                                       deepest_level = obj.get_level() + 1
+                               else:
+                                       deepest_level = obj.get_level() - root.get_level()
                                
                                # Could there be a deeper one?
                                if obj.is_leaf_node():
@@ -387,7 +398,7 @@ class TreeManager(models.Manager):
                # can be reduced. It might be possible to weight the search towards the beginning
                # of the path, since short paths are more likely, but how far forward? It would
                # need to shift depending on len(segments) - perhaps logarithmically?
-               return find_obj(segments, len(segments)/2 or len(segments), root)
+               return find_obj(segments, len(segments)/2 or len(segments))
 
 
 class TreeModel(MPTTModel):
@@ -396,10 +407,18 @@ class TreeModel(MPTTModel):
        slug = models.SlugField(max_length=255)
        
        def get_path(self, root=None, pathsep='/', field='slug'):
+               if root == self:
+                       return ''
+               
                if root is not None and not self.is_descendant_of(root):
                        raise AncestorDoesNotExist(root)
                
-               return pathsep.join([getattr(parent, field, '?') for parent in list(self.get_ancestors()) + [self]])
+               qs = self.get_ancestors()
+               
+               if root is not None:
+                       qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
+               
+               return pathsep.join([getattr(parent, field, '?') for parent in list(qs) + [self]])
        path = property(get_path)
        
        def __unicode__(self):