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 smart_str
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 value_content_type_limiter = ContentTypeRegistryLimiter()
44 def register_value_model(model):
45 value_content_type_limiter.register_class(model)
48 def unregister_value_model(model):
49 value_content_type_limiter.unregister_class(model)
52 class AttributeValue(models.Model):
53 attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
57 return self.attribute_set.all()[0]
59 def set_value(self, value):
60 raise NotImplementedError
62 def value_formfields(self, **kwargs):
63 """Define any formfields that would be used to construct an instance of this value."""
64 raise NotImplementedError
66 def construct_instance(self, **kwargs):
67 """Apply cleaned data from the formfields generated by valid_formfields to oneself."""
68 raise NotImplementedError
70 def __unicode__(self):
71 return unicode(self.value)
77 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
80 class JSONValue(AttributeValue):
81 value = JSONField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.', default='null')
83 def __unicode__(self):
84 return smart_str(self.value)
86 def value_formfields(self):
87 kwargs = {'initial': self.value_json}
88 field = self._meta.get_field('value')
89 return {field.name: field.formfield(**kwargs)}
91 def construct_instance(self, **kwargs):
92 field_name = self._meta.get_field('value').name
93 self.set_value(kwargs.pop(field_name, None))
95 def set_value(self, value):
102 class ForeignKeyValue(AttributeValue):
103 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
104 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
105 value = generic.GenericForeignKey()
107 def value_formfields(self):
108 field = self._meta.get_field('content_type')
109 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
111 if self.content_type:
113 'initial': self.object_id,
115 'queryset': self.content_type.model_class()._default_manager.all()
117 fields['value'] = forms.ModelChoiceField(**kwargs)
120 def construct_instance(self, **kwargs):
121 field_name = self._meta.get_field('content_type').name
122 ct = kwargs.pop(field_name, None)
123 if ct is None or ct != self.content_type:
124 self.object_id = None
125 self.content_type = ct
127 value = kwargs.pop('value', None)
128 self.set_value(value)
130 self.content_type = ct
132 def set_value(self, value):
139 class ManyToManyValue(AttributeValue):
140 content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
141 values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
143 def get_object_ids(self):
144 return self.values.values_list('object_id', flat=True)
145 object_ids = property(get_object_ids)
147 def set_value(self, value):
148 # Value must be a queryset. Watch out for ModelMultipleChoiceField;
149 # it returns its value as a list if empty.
151 self.content_type = ContentType.objects.get_for_model(value.model)
153 # Before we can fiddle with the many-to-many to foreignkeyvalues, we need
158 object_ids = value.values_list('id', flat=True)
160 # These lines shouldn't be necessary; however, if object_ids is an EmptyQuerySet,
161 # the code (specifically the object_id__in query) won't work without them. Unclear why...
162 # TODO: is this still the case?
164 self.values.all().delete()
166 self.values.exclude(object_id__in=object_ids, content_type=self.content_type).delete()
168 current_ids = self.object_ids
170 for object_id in object_ids:
171 if object_id in current_ids:
173 self.values.create(content_type=self.content_type, object_id=object_id)
176 if self.content_type is None:
179 # HACK to be safely explicit until http://code.djangoproject.com/ticket/15145 is resolved
180 object_ids = self.object_ids
181 manager = self.content_type.model_class()._default_manager
183 return manager.none()
184 return manager.filter(id__in=self.object_ids)
186 value = property(get_value, set_value)
188 def value_formfields(self):
189 field = self._meta.get_field('content_type')
190 fields = {field.name: field.formfield(initial=getattr(self.content_type, 'pk', None))}
192 if self.content_type:
194 'initial': self.object_ids,
196 'queryset': self.content_type.model_class()._default_manager.all()
198 fields['value'] = forms.ModelMultipleChoiceField(**kwargs)
201 def construct_instance(self, **kwargs):
202 field_name = self._meta.get_field('content_type').name
203 ct = kwargs.pop(field_name, None)
204 if ct is None or ct != self.content_type:
206 self.content_type = ct
208 value = kwargs.get('value', None)
210 value = self.content_type.model_class()._default_manager.none()
211 self.set_value(value)
212 construct_instance.alters_data = True
218 class Attribute(models.Model):
219 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
220 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
221 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
223 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)
224 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
225 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
227 key = models.CharField(max_length=255, validators=[RegexValidator("\w+")], help_text="Must contain one or more alphanumeric characters or underscores.")
229 def __unicode__(self):
230 return u'"%s": %s' % (self.key, self.value)
234 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
237 class QuerySetMapper(object, DictMixin):
238 def __init__(self, queryset, passthrough=None):
239 self.queryset = queryset
240 self.passthrough = passthrough
242 def __getitem__(self, key):
244 value = self.queryset.get(key__exact=key).value
245 except ObjectDoesNotExist:
246 if self.passthrough is not None:
247 return self.passthrough.__getitem__(key)
250 if value is not None:
255 keys = set(self.queryset.values_list('key', flat=True).distinct())
256 if self.passthrough is not None:
257 keys |= set(self.passthrough.keys())
261 class EntityOptions(object):
262 def __init__(self, options):
263 if options is not None:
264 for key, value in options.__dict__.items():
265 setattr(self, key, value)
266 if not hasattr(self, 'proxy_fields'):
267 self.proxy_fields = []
269 def add_proxy_field(self, proxy_field):
270 self.proxy_fields.append(proxy_field)
273 class EntityBase(models.base.ModelBase):
274 def __new__(cls, name, bases, attrs):
275 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
276 entity_options = attrs.pop('EntityMeta', None)
277 setattr(new, '_entity_meta', EntityOptions(entity_options))
278 entity_class_prepared.send(sender=new)
282 class Entity(models.Model):
283 __metaclass__ = EntityBase
285 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
288 def attributes(self):
289 return QuerySetMapper(self.attribute_set.all())
295 class TreeManager(models.Manager):
296 use_for_related_fields = True
298 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/', field='slug'):
300 Returns the object with the path, unless absolute_result is set to False, in which
301 case it returns a tuple containing the deepest object found along the path, and the
302 remainder of the path after that object as a string (or None if there is no remaining
303 path). Raises a DoesNotExist exception if no object is found with the given path.
305 If the path you're searching for is known to exist, it is always faster to use
306 absolute_result=True - unless the path depth is over ~40, in which case the high cost
307 of the absolute query makes a binary search (i.e. non-absolute) faster.
309 # Note: SQLite allows max of 64 tables in one join. That means the binary search will
310 # only work on paths with a max depth of 127 and the absolute fetch will only work
311 # to a max depth of (surprise!) 63. Although this could be handled, chances are your
312 # tree structure won't be that deep.
313 segments = path.split(pathsep)
315 # Check for a trailing pathsep so we can restore it later.
316 trailing_pathsep = False
317 if segments[-1] == '':
318 trailing_pathsep = True
320 # Clean out blank segments. Handles multiple consecutive pathseps.
327 # Special-case a lack of segments. No queries necessary.
334 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
336 def make_query_kwargs(segments, root):
339 revsegs = list(segments)
342 for segment in revsegs:
343 kwargs["%s%s__exact" % (prefix, field)] = segment
347 kwargs[prefix[:-2]] = root
351 def build_path(segments):
352 path = pathsep.join(segments)
353 if trailing_pathsep and segments and segments[-1] != '':
357 def find_obj(segments, depth, deepest_found=None):
358 if deepest_found is None:
361 deepest_level = deepest_found.get_level() + 1
363 deepest_level = deepest_found.get_level() - root.get_level()
365 obj = self.get(**make_query_kwargs(segments[deepest_level:depth], deepest_found or root))
366 except self.model.DoesNotExist:
367 if not deepest_level and depth > 1:
368 # make sure there's a root node...
371 # Try finding one with half the path since the deepest find.
372 depth = (deepest_level + depth)/2
374 if deepest_level == depth:
375 # This should happen if nothing is found with any part of the given path.
376 if root is not None and deepest_found is None:
377 return root, build_path(segments)
380 return find_obj(segments, depth, deepest_found)
384 deepest_level = obj.get_level() + 1
386 deepest_level = obj.get_level() - root.get_level()
388 # Could there be a deeper one?
389 if obj.is_leaf_node():
390 return obj, build_path(segments[deepest_level:]) or None
392 depth += (len(segments) - depth)/2 or len(segments) - depth
394 if depth > deepest_level + obj.get_descendant_count():
395 depth = deepest_level + obj.get_descendant_count()
397 if deepest_level == depth:
398 return obj, build_path(segments[deepest_level:]) or None
401 return find_obj(segments, depth, obj)
402 except self.model.DoesNotExist:
403 # Then this was the deepest.
404 return obj, build_path(segments[deepest_level:])
407 return self.get(**make_query_kwargs(segments, root))
409 # Try a modified binary search algorithm. Feed the root in so that query complexity
410 # can be reduced. It might be possible to weight the search towards the beginning
411 # of the path, since short paths are more likely, but how far forward? It would
412 # need to shift depending on len(segments) - perhaps logarithmically?
413 return find_obj(segments, len(segments)/2 or len(segments))
416 class TreeModel(MPTTModel):
417 objects = TreeManager()
418 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
419 slug = models.SlugField(max_length=255)
421 def get_path(self, root=None, pathsep='/', field='slug'):
425 if root is not None and not self.is_descendant_of(root):
426 raise AncestorDoesNotExist(root)
428 qs = self.get_ancestors(include_self=True)
431 qs = qs.filter(**{'%s__gt' % self._mptt_meta.level_attr: root.get_level()})
433 return pathsep.join([getattr(parent, field, '?') for parent in qs])
434 path = property(get_path)
436 def __unicode__(self):
440 unique_together = (('parent', 'slug'),)
444 class TreeEntityBase(MPTTModelBase, EntityBase):
445 def __new__(meta, name, bases, attrs):
446 attrs['_mptt_meta'] = MPTTOptions(attrs.pop('MPTTMeta', None))
447 cls = EntityBase.__new__(meta, name, bases, attrs)
449 return meta.register(cls)
452 class TreeEntity(Entity, TreeModel):
453 __metaclass__ = TreeEntityBase
456 def attributes(self):
458 return QuerySetMapper(self.attribute_set.all(), passthrough=self.parent.attributes)
459 return super(TreeEntity, self).attributes