Slight changes to penfield NewsletterIssueAdmin & added newsletter value models
[philo.git] / models / base.py
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
8
9
10 class Tag(models.Model):
11         name = models.CharField(max_length=250)
12         slug = models.SlugField(unique=True)
13         
14         def __unicode__(self):
15                 return self.name
16         
17         class Meta:
18                 app_label = 'philo'
19
20
21 class Titled(models.Model):
22         title = models.CharField(max_length=255)
23         slug = models.SlugField(max_length=255)
24         
25         def __unicode__(self):
26                 return self.title
27         
28         class Meta:
29                 abstract = True
30
31
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.')
38         
39         def get_value(self):
40                 return json.loads(self.json_value)
41         
42         def set_value(self, value):
43                 self.json_value = json.dumps(value)
44         
45         def delete_value(self):
46                 self.json_value = json.dumps(None)
47         
48         value = property(get_value, set_value, delete_value)
49         
50         def __unicode__(self):
51                 return u'"%s": %s' % (self.key, self.value)
52         
53         class Meta:
54                 app_label = 'philo'
55
56
57 value_content_type_limiter = ContentTypeRegistryLimiter()
58
59
60 def register_value_model(model):
61         value_content_type_limiter.register_class(model)
62
63
64 def unregister_value_model(model):
65         value_content_type_limiter.unregister_class(model)
66
67
68
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')
77         
78         def __unicode__(self):
79                 return u'"%s": %s' % (self.key, self.value)
80         
81         class Meta:
82                 app_label = 'philo'
83
84
85 class QuerySetMapper(object, DictMixin):
86         def __init__(self, queryset, passthrough=None):
87                 self.queryset = queryset
88                 self.passthrough = passthrough
89         
90         def __getitem__(self, key):
91                 try:
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)
96                         raise KeyError
97         
98         def keys(self):
99                 keys = set(self.queryset.values_list('key', flat=True).distinct())
100                 if self.passthrough is not None:
101                         keys |= set(self.passthrough.keys())
102                 return list(keys)
103
104
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')
108         
109         @property
110         def attributes(self):
111                 return QuerySetMapper(self.attribute_set)
112         
113         @property
114         def relationships(self):
115                 return QuerySetMapper(self.relationship_set)
116         
117         class Meta:
118                 abstract = True
119
120
121 class TreeManager(models.Manager):
122         use_for_related_fields = True
123         
124         def roots(self):
125                 return self.filter(parent__isnull=True)
126         
127         def get_with_path(self, path, root=None, absolute_result=True, pathsep='/'):
128                 """
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).
133                 """
134                 slugs = path.split(pathsep)
135                 obj = root
136                 remaining_slugs = list(slugs)
137                 remainder = None
138                 for slug in slugs:
139                         remaining_slugs.remove(slug)
140                         if slug: # ignore blank slugs, handles for multiple consecutive pathseps
141                                 try:
142                                         obj = self.get(slug__exact=slug, parent__exact=obj)
143                                 except self.model.DoesNotExist:
144                                         if absolute_result:
145                                                 obj = None
146                                         remaining_slugs.insert(0, slug)
147                                         remainder = pathsep.join(remaining_slugs)
148                                         break
149                 if obj:
150                         if absolute_result:
151                                 return obj
152                         else:
153                                 return (obj, remainder)
154                 raise self.model.DoesNotExist('%s matching query does not exist.' % self.model._meta.object_name)
155
156
157 class TreeModel(models.Model):
158         objects = TreeManager()
159         parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
160         slug = models.SlugField()
161         
162         def has_ancestor(self, ancestor):
163                 parent = self
164                 while parent:
165                         if parent == ancestor:
166                                 return True
167                         parent = parent.parent
168                 return False
169         
170         def get_path(self, root=None, pathsep='/', field='slug'):
171                 if root is not None and self.has_ancestor(root):
172                         path = ''
173                         parent = self
174                         while parent and parent != root:
175                                 path = getattr(parent, field, '?') + pathsep + path
176                                 parent = parent.parent
177                         return path
178                 else:
179                         path = getattr(self, field, '?')
180                         parent = self.parent
181                         while parent and parent != root:
182                                 path = getattr(parent, field, '?') + pathsep + path
183                                 parent = parent.parent
184                         return path
185         path = property(get_path)
186         
187         def __unicode__(self):
188                 return self.path
189         
190         class Meta:
191                 unique_together = (('parent', 'slug'),)
192                 abstract = True
193
194
195 class TreeEntity(TreeModel, Entity):
196         @property
197         def attributes(self):
198                 if self.parent:
199                         return QuerySetMapper(self.attribute_set, passthrough=self.parent.attributes)
200                 return super(TreeEntity, self).attributes
201         
202         @property
203         def relationships(self):
204                 if self.parent:
205                         return QuerySetMapper(self.relationship_set, passthrough=self.parent.relationships)
206                 return super(TreeEntity, self).relationships
207         
208         class Meta:
209                 abstract = True