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