1 from django.db import models
2 from django.contrib.contenttypes.models import ContentType
3 from django.contrib.contenttypes import generic
4 from django.utils import simplejson as json
5 from django.core.exceptions import ObjectDoesNotExist
6 from philo.utils import ContentTypeRegistryLimiter
7 from UserDict import DictMixin
10 class Tag(models.Model):
11 name = models.CharField(max_length=250)
12 slug = models.SlugField(unique=True)
14 def __unicode__(self):
21 class Titled(models.Model):
22 title = models.CharField(max_length=255)
23 slug = models.SlugField(max_length=255)
25 def __unicode__(self):
32 class Attribute(models.Model):
33 entity_content_type = models.ForeignKey(ContentType, verbose_name='Entity type')
34 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
35 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
36 key = models.CharField(max_length=255)
37 json_value = models.TextField(verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
40 return json.loads(self.json_value)
42 def set_value(self, value):
43 self.json_value = json.dumps(value)
45 def delete_value(self):
46 self.json_value = json.dumps(None)
48 value = property(get_value, set_value, delete_value)
50 def __unicode__(self):
51 return u'"%s": %s' % (self.key, self.value)
57 value_content_type_limiter = ContentTypeRegistryLimiter()
60 def register_value_model(model):
61 value_content_type_limiter.register_class(model)
64 def unregister_value_model(model):
65 value_content_type_limiter.unregister_class(model)
69 class Relationship(models.Model):
70 entity_content_type = models.ForeignKey(ContentType, related_name='relationship_entity_set', verbose_name='Entity type')
71 entity_object_id = models.PositiveIntegerField(verbose_name='Entity ID')
72 entity = generic.GenericForeignKey('entity_content_type', 'entity_object_id')
73 key = models.CharField(max_length=255)
74 value_content_type = models.ForeignKey(ContentType, related_name='relationship_value_set', limit_choices_to=value_content_type_limiter, verbose_name='Value type')
75 value_object_id = models.PositiveIntegerField(verbose_name='Value ID')
76 value = generic.GenericForeignKey('value_content_type', 'value_object_id')
78 def __unicode__(self):
79 return u'"%s": %s' % (self.key, self.value)
85 class QuerySetMapper(object, DictMixin):
86 def __init__(self, queryset, passthrough=None):
87 self.queryset = queryset
88 self.passthrough = passthrough
90 def __getitem__(self, key):
92 return self.queryset.get(key__exact=key).value
93 except ObjectDoesNotExist:
94 if self.passthrough is not None:
95 return self.passthrough.__getitem__(key)
99 keys = set(self.queryset.values_list('key', flat=True).distinct())
100 if self.passthrough is not None:
101 keys |= set(self.passthrough.keys())
105 class Entity(models.Model):
106 attribute_set = generic.GenericRelation(Attribute, content_type_field='entity_content_type', object_id_field='entity_object_id')
107 relationship_set = generic.GenericRelation(Relationship, content_type_field='entity_content_type', object_id_field='entity_object_id')
110 def attributes(self):
111 return QuerySetMapper(self.attribute_set)
114 def relationships(self):
115 return QuerySetMapper(self.relationship_set)
121 class TreeManager(models.Manager):
122 use_for_related_fields = True
125 return self.filter(parent__isnull=True)
127 def get_with_path(self, path, root=None, absolute_result=True, pathsep='/'):
129 Returns the object with the path, or None if there is no object with that path,
130 unless absolute_result is set to False, in which case it returns a tuple containing
131 the deepest object found along the path, and the remainder of the path after that
132 object as a string (or None in the case that there is no remaining path).
134 slugs = path.split(pathsep)
136 remaining_slugs = list(slugs)
139 remaining_slugs.remove(slug)
140 if slug: # ignore blank slugs, handles for multiple consecutive pathseps
142 obj = self.get(slug__exact=slug, parent__exact=obj)
143 except self.model.DoesNotExist:
146 remaining_slugs.insert(0, slug)
147 remainder = pathsep.join(remaining_slugs)
153 return (obj, remainder)
154 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
157 class TreeModel(models.Model):
158 objects = TreeManager()
159 parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
160 slug = models.SlugField()
162 def has_ancestor(self, ancestor):
165 if parent == ancestor:
167 parent = parent.parent
170 def get_path(self, root=None, pathsep='/', field='slug'):
171 if root is not None and self.has_ancestor(root):
174 while parent and parent != root:
175 path = getattr(parent, field, '?') + pathsep + path
176 parent = parent.parent
179 path = getattr(self, field, '?')
181 while parent and parent != root:
182 path = getattr(parent, field, '?') + pathsep + path
183 parent = parent.parent
185 path = property(get_path)
187 def __unicode__(self):
191 unique_together = (('parent', 'slug'),)
195 class TreeEntity(TreeModel, Entity):
197 def attributes(self):
199 return QuerySetMapper(self.attribute_set, passthrough=self.parent.attributes)
200 return super(TreeEntity, self).attributes
203 def relationships(self):
205 return QuerySetMapper(self.relationship_set, passthrough=self.parent.relationships)
206 return super(TreeEntity, self).relationships