Added support for 'editable' to ProxyFields. Tweaked AttributeFieldDescriptor base...
[philo.git] / models / base.py
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
13
14
15 class Tag(models.Model):
16         name = models.CharField(max_length=255)
17         slug = models.SlugField(max_length=255, unique=True)
18         
19         def __unicode__(self):
20                 return self.name
21         
22         class Meta:
23                 app_label = 'philo'
24
25
26 class Titled(models.Model):
27         title = models.CharField(max_length=255)
28         slug = models.SlugField(max_length=255)
29         
30         def __unicode__(self):
31                 return self.title
32         
33         class Meta:
34                 abstract = True
35
36
37 value_content_type_limiter = ContentTypeRegistryLimiter()
38
39
40 def register_value_model(model):
41         value_content_type_limiter.register_class(model)
42
43
44 def unregister_value_model(model):
45         value_content_type_limiter.unregister_class(model)
46
47
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
52         
53         def value_formfield(self, **kwargs):
54                 raise NotImplementedError
55         
56         def __unicode__(self):
57                 return unicode(self.value)
58         
59         class Meta:
60                 abstract = True
61
62
63 attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
64
65
66 class JSONValue(AttributeValue):
67         value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
68         
69         def __unicode__(self):
70                 return self.value_json
71         
72         def value_formfield(self, **kwargs):
73                 kwargs['initial'] = self.value_json
74                 return self._meta.get_field('value').formfield(**kwargs)
75         
76         def apply_data(self, cleaned_data):
77                 self.value = cleaned_data.get('value', None)
78         
79         class Meta:
80                 app_label = 'philo'
81
82
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()
87         
88         def value_formfield(self, form_class=forms.ModelChoiceField, **kwargs):
89                 if self.content_type is None:
90                         return None
91                 kwargs.update({'initial': self.object_id, 'required': False})
92                 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
93         
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']
97                 else:
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
101         
102         class Meta:
103                 app_label = 'philo'
104
105
106 class ManyToManyValue(AttributeValue):
107         # TODO: Change object_ids to object_pks.
108         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)
109         object_ids = models.CommaSeparatedIntegerField(max_length=300, verbose_name='Value IDs', null=True, blank=True)
110         
111         def get_object_id_list(self):
112                 if not self.object_ids:
113                         return []
114                 else:
115                         return self.object_ids.split(',')
116         
117         def get_value(self):
118                 if self.content_type is None:
119                         return None
120                 
121                 return self.content_type.model_class()._default_manager.filter(id__in=self.get_object_id_list())
122         
123         def set_value(self, value):
124                 if value is None:
125                         self.object_ids = ""
126                         return
127                 if not isinstance(value, models.query.QuerySet):
128                         raise TypeError("Value must be a QuerySet.")
129                 self.content_type = ContentType.objects.get_for_model(value.model)
130                 self.object_ids = ','.join([`value` for value in value.values_list('id', flat=True)])
131         
132         value = property(get_value, set_value)
133         
134         def value_formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
135                 if self.content_type is None:
136                         return None
137                 kwargs.update({'initial': self.get_object_id_list(), 'required': False})
138                 return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
139         
140         def apply_data(self, cleaned_data):
141                 if 'value' in cleaned_data and cleaned_data['value'] is not None:
142                         self.value = cleaned_data['value']
143                 else:
144                         self.content_type = cleaned_data.get('content_type', None)
145                         # If there is no value set in the cleaned data, clear the stored value.
146                         self.object_ids = ""
147         
148         class Meta:
149                 app_label = 'philo'
150
151
152 class Attribute(models.Model):
153         entity_content_type = models.ForeignKey(ContentType, related_name='attribute_entity_set', verbose_name='Entity type')
154         entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
155         entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
156         
157         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)
158         value_object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
159         value = generic.GenericForeignKey('value_content_type', 'value_object_id')
160         
161         key = models.CharField(max_length=255)
162         
163         def __unicode__(self):
164                 return u'"%s": %s' % (self.key, self.value)
165         
166         class Meta:
167                 app_label = 'philo'
168                 unique_together = (('key', 'entity_content_type', 'entity_object_id'), ('value_content_type', 'value_object_id'))
169
170
171 class QuerySetMapper(object, DictMixin):
172         def __init__(self, queryset, passthrough=None):
173                 self.queryset = queryset
174                 self.passthrough = passthrough
175         
176         def __getitem__(self, key):
177                 try:
178                         value = self.queryset.get(key__exact=key).value
179                 except ObjectDoesNotExist:
180                         if self.passthrough is not None:
181                                 return self.passthrough.__getitem__(key)
182                         raise KeyError
183                 else:
184                         if value is not None:
185                                 return value.value
186                         return value
187         
188         def keys(self):
189                 keys = set(self.queryset.values_list('key', flat=True).distinct())
190                 if self.passthrough is not None:
191                         keys |= set(self.passthrough.keys())
192                 return list(keys)
193
194
195 class EntityOptions(object):
196         def __init__(self, options):
197                 if options is not None:
198                         for key, value in options.__dict__.items():
199                                 setattr(self, key, value)
200                 if not hasattr(self, 'proxy_fields'):
201                         self.proxy_fields = []
202         
203         def add_proxy_field(self, proxy_field):
204                 self.proxy_fields.append(proxy_field)
205
206
207 class EntityBase(models.base.ModelBase):
208         def __new__(cls, name, bases, attrs):
209                 new = super(EntityBase, cls).__new__(cls, name, bases, attrs)
210                 entity_options = attrs.pop('EntityMeta', None)
211                 setattr(new, '_entity_meta', EntityOptions(entity_options))
212                 entity_class_prepared.send(sender=new)
213                 return new
214
215
216 class Entity(models.Model):
217         __metaclass__ = EntityBase
218         
219         attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
220         
221         @property
222         def attributes(self):
223                 return QuerySetMapper(self.attribute_set)
224         
225         @property
226         def _added_attribute_registry(self):
227                 if not hasattr(self, '_real_added_attribute_registry'):
228                         self._real_added_attribute_registry = {}
229                 return self._real_added_attribute_registry
230         
231         @property
232         def _removed_attribute_registry(self):
233                 if not hasattr(self, '_real_removed_attribute_registry'):
234                         self._real_removed_attribute_registry = []
235                 return self._real_removed_attribute_registry
236         
237         def save(self, *args, **kwargs):
238                 super(Entity, self).save(*args, **kwargs)
239                 
240                 for key in self._removed_attribute_registry:
241                         self.attribute_set.filter(key__exact=key).delete()
242                 del self._removed_attribute_registry[:]
243                 
244                 for field, value in self._added_attribute_registry.items():
245                         try:
246                                 attribute = self.attribute_set.get(key__exact=field.key)
247                         except Attribute.DoesNotExist:
248                                 attribute = Attribute()
249                                 attribute.entity = self
250                                 attribute.key = field.key
251                         
252                         field.set_attribute_value(attribute, value)
253                         attribute.save()
254                 self._added_attribute_registry.clear()
255         
256         class Meta:
257                 abstract = True
258
259
260 class TreeManager(models.Manager):
261         use_for_related_fields = True
262         
263         def roots(self):
264                 return self.filter(parent__isnull=True)
265         
266         def get_with_path(self, path, root=None, absolute_result=True, pathsep='/'):
267                 """
268                 Returns the object with the path, or None if there is no object with that path,
269                 unless absolute_result is set to False, in which case it returns a tuple containing
270                 the deepest object found along the path, and the remainder of the path after that
271                 object as a string (or None in the case that there is no remaining path).
272                 """
273                 slugs = path.split(pathsep)
274                 obj = root
275                 remaining_slugs = list(slugs)
276                 remainder = None
277                 for slug in slugs:
278                         remaining_slugs.remove(slug)
279                         if slug: # ignore blank slugs, handles for multiple consecutive pathseps
280                                 try:
281                                         obj = self.get(slug__exact=slug, parent__exact=obj)
282                                 except self.model.DoesNotExist:
283                                         if absolute_result:
284                                                 obj = None
285                                         remaining_slugs.insert(0, slug)
286                                         remainder = pathsep.join(remaining_slugs)
287                                         break
288                 if obj:
289                         if absolute_result:
290                                 return obj
291                         else:
292                                 return (obj, remainder)
293                 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
294
295
296 class TreeModel(models.Model):
297         objects = TreeManager()
298         parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
299         slug = models.SlugField(max_length=255)
300         
301         def has_ancestor(self, ancestor):
302                 parent = self
303                 while parent:
304                         if parent == ancestor:
305                                 return True
306                         parent = parent.parent
307                 return False
308         
309         def get_path(self, root=None, pathsep='/', field='slug'):
310                 if root is not None:
311                         if not self.has_ancestor(root):
312                                 raise AncestorDoesNotExist(root)
313                         path = ''
314                         parent = self
315                         while parent and parent != root:
316                                 path = getattr(parent, field, '?') + pathsep + path
317                                 parent = parent.parent
318                         return path
319                 else:
320                         path = getattr(self, field, '?')
321                         parent = self.parent
322                         while parent and parent != root:
323                                 path = getattr(parent, field, '?') + pathsep + path
324                                 parent = parent.parent
325                         return path
326         path = property(get_path)
327         
328         def __unicode__(self):
329                 return self.path
330         
331         class Meta:
332                 unique_together = (('parent', 'slug'),)
333                 abstract = True
334
335
336 class TreeEntity(Entity, TreeModel):
337         @property
338         def attributes(self):
339                 if self.parent:
340                         return QuerySetMapper(self.attribute_set, passthrough=self.parent.attributes)
341                 return super(TreeEntity, self).attributes
342         
343         @property
344         def relationships(self):
345                 if self.parent:
346                         return QuerySetMapper(self.relationship_set, passthrough=self.parent.relationships)
347                 return super(TreeEntity, self).relationships
348         
349         class Meta:
350                 abstract = True