d9f3c8a75bc1903bd1a49b84289546da1e825256
[philo.git] / contrib / cowell / fields.py
1 """
2 The Attributes defined in this file can be assigned as fields on a proxy of
3 a subclass of philo.models.Entity. They act like any other model fields,
4 but instead of saving their data to the database, they save it to
5 attributes related to a model instance. Additionally, a new attribute will
6 be created for an instance if and only if the field's value has been set.
7 This is relevant i.e. for passthroughs, where the value of the field may
8 be defined by some other instance's attributes.
9
10 Example::
11
12         class Thing(Entity):
13                 numbers = models.PositiveIntegerField()
14         
15         class ThingProxy(Thing):
16                 improvised = JSONAttribute(models.BooleanField)
17                 
18                 class Meta:
19                         proxy = True
20 """
21 from django import forms
22 from django.core.exceptions import FieldError
23 from django.db import models
24 from django.db.models.fields import NOT_PROVIDED
25 from django.utils.text import capfirst
26 from philo.signals import entity_class_prepared
27 from philo.models import ManyToManyValue, JSONValue, ForeignKeyValue, Attribute, Entity
28
29
30 __all__ = ('JSONAttribute', 'ForeignKeyAttribute', 'ManyToManyAttribute')
31
32
33 ATTRIBUTE_REGISTRY = '_attribute_registry'
34
35
36 class EntityProxyField(object):
37         def __init__(self, verbose_name=None, help_text=None, default=NOT_PROVIDED, editable=True, *args, **kwargs):
38                 self.verbose_name = verbose_name
39                 self.help_text = help_text
40                 self.default = default
41                 self.editable = editable
42         
43         def actually_contribute_to_class(self, sender, **kwargs):
44                 sender._entity_meta.add_proxy_field(self)
45         
46         def contribute_to_class(self, cls, name):
47                 if issubclass(cls, Entity):
48                         self.name = self.attname = name
49                         self.model = cls
50                         if self.verbose_name is None and name:
51                                 self.verbose_name = name.replace('_', ' ')
52                         entity_class_prepared.connect(self.actually_contribute_to_class, sender=cls)
53                 else:
54                         raise FieldError('%s instances can only be declared on Entity subclasses.' % self.__class__.__name__)
55         
56         def formfield(self, form_class=forms.CharField, **kwargs):
57                 defaults = {
58                         'required': False,
59                         'label': capfirst(self.verbose_name),
60                         'help_text': self.help_text
61                 }
62                 if self.has_default():
63                         defaults['initial'] = self.default
64                 defaults.update(kwargs)
65                 return form_class(**defaults)
66         
67         def value_from_object(self, obj):
68                 """The return value of this method will be used by the EntityForm as
69                 this field's initial value."""
70                 return getattr(obj, self.name)
71         
72         def has_default(self):
73                 return self.default is not NOT_PROVIDED
74
75
76 class AttributeFieldDescriptor(object):
77         def __init__(self, field):
78                 self.field = field
79         
80         def get_registry(self, instance):
81                 if ATTRIBUTE_REGISTRY not in instance.__dict__:
82                         instance.__dict__[ATTRIBUTE_REGISTRY] = {'added': set(), 'removed': set()}
83                 return instance.__dict__[ATTRIBUTE_REGISTRY]
84         
85         def __get__(self, instance, owner):
86                 if instance is None:
87                         return self
88                 
89                 if self.field.name not in instance.__dict__:
90                         instance.__dict__[self.field.name] = instance.attributes.get(self.field.attribute_key, None)
91                 
92                 return instance.__dict__[self.field.name]
93         
94         def __set__(self, instance, value):
95                 if instance is None:
96                         raise AttributeError("%s must be accessed via instance" % self.field.name)
97                 
98                 self.field.validate_value(value)
99                 instance.__dict__[self.field.name] = value
100                 
101                 registry = self.get_registry(instance)
102                 registry['added'].add(self.field)
103                 registry['removed'].discard(self.field)
104         
105         def __delete__(self, instance):
106                 del instance.__dict__[self.field.name]
107                 
108                 registry = self.get_registry(instance)
109                 registry['added'].discard(self.field)
110                 registry['removed'].add(self.field)
111
112
113 def process_attribute_fields(sender, instance, created, **kwargs):
114         if ATTRIBUTE_REGISTRY in instance.__dict__:
115                 registry = instance.__dict__[ATTRIBUTE_REGISTRY]
116                 instance.attribute_set.filter(key__in=[field.attribute_key for field in registry['removed']]).delete()
117                 
118                 for field in registry['added']:
119                         try:
120                                 attribute = instance.attribute_set.get(key=field.attribute_key)
121                         except Attribute.DoesNotExist:
122                                 attribute = Attribute()
123                                 attribute.entity = instance
124                                 attribute.key = field.attribute_key
125                         
126                         value_class = field.value_class
127                         if isinstance(attribute.value, value_class):
128                                 value = attribute.value
129                         else:
130                                 if isinstance(attribute.value, models.Model):
131                                         attribute.value.delete()
132                                 value = value_class()
133                         
134                         value.set_value(getattr(instance, field.name, None))
135                         value.save()
136                         
137                         attribute.value = value
138                         attribute.save()
139                 del instance.__dict__[ATTRIBUTE_REGISTRY]
140
141
142 class AttributeField(EntityProxyField):
143         def __init__(self, attribute_key=None, **kwargs):
144                 self.attribute_key = attribute_key
145                 super(AttributeField, self).__init__(**kwargs)
146         
147         def actually_contribute_to_class(self, sender, **kwargs):
148                 super(AttributeField, self).actually_contribute_to_class(sender, **kwargs)
149                 setattr(sender, self.name, AttributeFieldDescriptor(self))
150                 opts = sender._entity_meta
151                 if not hasattr(opts, '_has_attribute_fields'):
152                         opts._has_attribute_fields = True
153                         models.signals.post_save.connect(process_attribute_fields, sender=sender)
154                 
155         
156         def contribute_to_class(self, cls, name):
157                 if self.attribute_key is None:
158                         self.attribute_key = name
159                 super(AttributeField, self).contribute_to_class(cls, name)
160         
161         def validate_value(self, value):
162                 "Confirm that the value is valid or raise an appropriate error."
163                 raise NotImplementedError("validate_value must be implemented by AttributeField subclasses.")
164         
165         @property
166         def value_class(self):
167                 raise AttributeError("value_class must be defined on AttributeField subclasses.")
168
169
170 class JSONAttribute(AttributeField):
171         value_class = JSONValue
172         
173         def __init__(self, field_template=None, **kwargs):
174                 super(JSONAttribute, self).__init__(**kwargs)
175                 if field_template is None:
176                         field_template = models.CharField(max_length=255)
177                 self.field_template = field_template
178         
179         def validate_value(self, value):
180                 pass
181         
182         def formfield(self, **kwargs):
183                 defaults = {
184                         'required': False,
185                         'label': capfirst(self.verbose_name),
186                         'help_text': self.help_text
187                 }
188                 if self.has_default():
189                         defaults['initial'] = self.default
190                 defaults.update(kwargs)
191                 return self.field_template.formfield(**defaults)
192
193
194 class ForeignKeyAttribute(AttributeField):
195         value_class = ForeignKeyValue
196         
197         def __init__(self, model, limit_choices_to=None, **kwargs):
198                 super(ForeignKeyAttribute, self).__init__(**kwargs)
199                 self.model = model
200                 if limit_choices_to is None:
201                         limit_choices_to = {}
202                 self.limit_choices_to = limit_choices_to
203         
204         def validate_value(self, value):
205                 if value is not None and not isinstance(value, self.model) :
206                         raise TypeError("The '%s' attribute can only be set to an instance of %s or None." % (self.name, self.model.__name__))
207         
208         def formfield(self, form_class=forms.ModelChoiceField, **kwargs):
209                 defaults = {
210                         'queryset': self.model._default_manager.complex_filter(self.limit_choices_to)
211                 }
212                 defaults.update(kwargs)
213                 return super(ForeignKeyAttribute, self).formfield(form_class=form_class, **defaults)
214         
215         def value_from_object(self, obj):
216                 relobj = super(ForeignKeyAttribute, self).value_from_object(obj)
217                 return getattr(relobj, 'pk', None)
218
219
220 class ManyToManyAttribute(ForeignKeyAttribute):
221         value_class = ManyToManyValue
222         
223         def validate_value(self, value):
224                 if not isinstance(value, models.query.QuerySet) or value.model != self.model:
225                         raise TypeError("The '%s' attribute can only be set to a %s QuerySet." % (self.name, self.model.__name__))
226         
227         def formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
228                 return super(ManyToManyAttribute, self).formfield(form_class=form_class, **kwargs)
229         
230         def value_from_object(self, obj):
231                 qs = super(ForeignKeyAttribute, self).value_from_object(obj)
232                 try:
233                         return qs.values_list('pk', flat=True)
234                 except:
235                         return []