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.utils import simplejson as json
6 from django.core.exceptions import ObjectDoesNotExist
7 from philo.exceptions import AncestorDoesNotExist
8 from philo.models.fields import JSONField
9 from philo.utils import ContentTypeRegistryLimiter, ContentTypeSubclassLimiter
10 from philo.signals import entity_class_prepared
11 from philo.validators import json_validator
12 from UserDict import DictMixin
15 class Tag(models.Model):
16 name = models.CharField(max_length=255)
17 slug = models.SlugField(max_length=255, unique=True)
19 def __unicode__(self):
26 class Titled(models.Model):
27 title = models.CharField(max_length=255)
28 slug = models.SlugField(max_length=255)
30 def __unicode__(self):
37 value_content_type_limiter = ContentTypeRegistryLimiter()
40 def register_value_model(model):
41 value_content_type_limiter.register_class(model)
44 def unregister_value_model(model):
45 value_content_type_limiter.unregister_class(model)
48 class AttributeValue(models.Model):
49 attribute = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
50 def apply_data(self, data):
51 raise NotImplementedError
53 def value_formfield(self, **kwargs):
54 raise NotImplementedError
56 def __unicode__(self):
57 return unicode(self.value)
63 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
66 class JSONValue(AttributeValue):
67 value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
69 def __unicode__(self):
70 return self.value_json
72 def value_formfield(self, **kwargs):
73 kwargs['initial'] = self.value_json
74 return self._meta.get_field('value').formfield(**kwargs)
76 def apply_data(self, cleaned_data):
77 self.value = cleaned_data.get('value', None)
83 class ForeignKeyValue(AttributeValue):
84 content_type = models.ForeignKey(ContentType, related_name='foreign_key_value_set', limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
85 object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
86 value = generic.GenericForeignKey()
88 def value_formfield(self, form_class=forms.ModelChoiceField, **kwargs):
89 if self.content_type is None:
91 kwargs.update({'initial': self.object_id, 'required': False})
92 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
94 def apply_data(self, cleaned_data):
95 if 'value' in cleaned_data and cleaned_data['value'] is not None:
96 self.value = cleaned_data['value']
98 self.content_type = cleaned_data.get('content_type', None)
99 # If there is no value set in the cleaned data, clear the stored value.
100 self.object_id = None
106 class ManyToManyValue(AttributeValue):
107 content_type = models.ForeignKey(ContentType, related_name='many_to_many_value_set', limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
108 object_ids = models.CommaSeparatedIntegerField(max_length=300, verbose_name='Value IDs', null=True, blank=True)
110 def get_object_id_list(self):
111 if not self.object_ids:
114 return self.object_ids.split(',')
117 if self.content_type is None:
120 return self.content_type.model_class()._default_manager.filter(id__in=self.get_object_id_list())
122 def set_value(self, value):
126 if not isinstance(value, models.query.QuerySet):
127 raise TypeError("Value must be a QuerySet.")
128 self.content_type = ContentType.objects.get_for_model(value.model)
129 self.object_ids = ','.join([`value` for value in value.values_list('id', flat=True)])
131 value = property(get_value, set_value)
133 def value_formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
134 if self.content_type is None:
136 kwargs.update({'initial': self.get_object_id_list(), 'required': False})
137 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
139 def apply_data(self, cleaned_data):
140 self.value = cleaned_data.get('value', None)
146 class Attribute(models.Model):
147 entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
148 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
149 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
151 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)
152 value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
153 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
155 key = models.CharField(max_length=255)
157 def get_value_class(self, value):
158 if isinstance(value, models.query.QuerySet):
159 return ManyToManyValue
160 elif isinstance(value, models.Model) or (value is None and self.value_content_type.model_class() is ForeignKeyValue):
161 return ForeignKeyValue
165 def set_value(self, value):
166 # is this useful? The best way of doing it?
167 value_class = self.get_value_class(value)
169 if self.value is None or value_class != self.value_content_type.model_class():
170 if self.value is not None:
172 new_value = value_class()
173 new_value.value = value
175 self.value = new_value
177 self.value.value = value
180 def __unicode__(self):
181 return u'"%s": %s' % (self.key, self.value)
185 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
188 class QuerySetMapper(object, DictMixin):
189 def __init__(self, queryset, passthrough=None):
190 self.queryset = queryset
191 self.passthrough = passthrough
193 def __getitem__(self, key):
195 return self.queryset.get(key__exact=key).value
196 except ObjectDoesNotExist:
197 if self.passthrough is not None:
198 return self.passthrough.__getitem__(key)
202 keys = set(self.queryset.values_list('key', flat=True).distinct())
203 if self.passthrough is not None:
204 keys |= set(self.passthrough.keys())
208 class EntityOptions(object):
209 def __init__(self, options):
210 if options is not None:
211 for key, value in options.__dict__.items():
212 setattr(self, key, value)
213 if not hasattr(self, 'proxy_fields'):
214 self.proxy_fields = []
216 def add_proxy_field(self, proxy_field):
217 self.proxy_fields.append(proxy_field)
220 class EntityBase(models.base.ModelBase):
221 def __new__(cls, name, bases, attrs):
222 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
223 entity_options = attrs.pop('EntityMeta', None)
224 setattr(new, '_entity_meta', EntityOptions(entity_options))
225 entity_class_prepared.send(sender=new)
229 class Entity(models.Model):
230 __metaclass__ = EntityBase
232 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
235 def attributes(self):
236 return QuerySetMapper(self.attribute_set)
239 def _added_attribute_registry(self):
240 if not hasattr(self, '_real_added_attribute_registry'):
241 self._real_added_attribute_registry = {}
242 return self._real_added_attribute_registry
245 def _removed_attribute_registry(self):
246 if not hasattr(self, '_real_removed_attribute_registry'):
247 self._real_removed_attribute_registry = []
248 return self._real_removed_attribute_registry
250 def save(self, *args, **kwargs):
251 super(Entity, self).save(*args, **kwargs)
253 for key in self._removed_attribute_registry:
254 self.attribute_set.filter(key__exact=key).delete()
255 del self._removed_attribute_registry[:]
257 for key, value in self._added_attribute_registry.items():
259 attribute = self.attribute_set.get(key__exact=key)
260 except Attribute.DoesNotExist:
261 attribute = Attribute()
262 attribute.entity = self
264 attribute.set_value(value)
266 self._added_attribute_registry.clear()
272 class TreeManager(models.Manager):
273 use_for_related_fields = True
276 return self.filter(parent__isnull=True)
278 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/'):
280 Returns the object with the path, or None if there is no object with that path,
281 unless absolute_result is set to False, in which case it returns a tuple containing
282 the deepest object found along the path, and the remainder of the path after that
283 object as a string (or None in the case that there is no remaining path).
285 slugs = path.split(pathsep)
287 remaining_slugs = list(slugs)
290 remaining_slugs.remove(slug)
291 if slug: # ignore blank slugs, handles for multiple consecutive pathseps
293 obj = self.get(slug__exact=slug, parent__exact=obj)
294 except self.model.DoesNotExist:
297 remaining_slugs.insert(0, slug)
298 remainder = pathsep.join(remaining_slugs)
304 return (obj, remainder)
305 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
308 class TreeModel(models.Model):
309 objects = TreeManager()
310 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
311 slug = models.SlugField(max_length=255)
313 def has_ancestor(self, ancestor):
316 if parent == ancestor:
318 parent = parent.parent
321 def get_path(self, root=None, pathsep='/', field='slug'):
323 if not self.has_ancestor(root):
324 raise AncestorDoesNotExist(root)
327 while parent and parent != root:
328 path = getattr(parent, field, '?') + pathsep + path
329 parent = parent.parent
332 path = getattr(self, field, '?')
334 while parent and parent != root:
335 path = getattr(parent, field, '?') + pathsep + path
336 parent = parent.parent
338 path = property(get_path)
340 def __unicode__(self):
344 unique_together = (('parent', 'slug'),)
348 class TreeEntity(Entity, TreeModel):
350 def attributes(self):
352 return QuerySetMapper(self.attribute_set, passthrough=self.parent.attributes)
353 return super(TreeEntity, self).attributes
356 def relationships(self):
358 return QuerySetMapper(self.relationship_set, passthrough=self.parent.relationships)
359 return super(TreeEntity, self).relationships