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.
13 numbers = models.PositiveIntegerField()
15 class ThingProxy(Thing):
16 improvised = JSONAttribute(models.BooleanField)
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
28 __all__ = ('JSONAttribute', 'ForeignKeyAttribute', 'ManyToManyAttribute')
31 ATTRIBUTE_REGISTRY = '_attribute_registry'
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 []
42 def actually_contribute_to_class(self, sender, **kwargs):
43 sender._entity_meta.add_proxy_field(self)
45 def contribute_to_class(self, cls, name):
46 if issubclass(cls, Entity):
47 self.name = self.attname = name
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)
53 raise FieldError('%s instances can only be declared on Entity subclasses.' % self.__class__.__name__)
55 def formfield(self, form_class=forms.CharField, **kwargs):
58 'label': capfirst(self.verbose_name),
59 'help_text': self.help_text
61 if self.has_default():
62 defaults['initial'] = self.default
63 defaults.update(kwargs)
64 return form_class(**defaults)
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)
71 def has_default(self):
72 return self.default is not NOT_PROVIDED
74 def _get_choices(self):
75 if hasattr(self._choices, 'next'):
76 choices, self._choices = tee(self._choices)
80 choices = property(_get_choices)
83 class AttributeFieldDescriptor(object):
84 def __init__(self, field):
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]
92 def __get__(self, instance, owner):
96 if self.field.name not in instance.__dict__:
97 instance.__dict__[self.field.name] = instance.attributes.get(self.field.attribute_key, None)
99 return instance.__dict__[self.field.name]
101 def __set__(self, instance, value):
103 raise AttributeError("%s must be accessed via instance" % self.field.name)
105 self.field.validate_value(value)
106 instance.__dict__[self.field.name] = value
108 registry = self.get_registry(instance)
109 registry['added'].add(self.field)
110 registry['removed'].discard(self.field)
112 def __delete__(self, instance):
113 del instance.__dict__[self.field.name]
115 registry = self.get_registry(instance)
116 registry['added'].discard(self.field)
117 registry['removed'].add(self.field)
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()
125 for field in registry['added']:
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
133 value_class = field.value_class
134 if isinstance(attribute.value, value_class):
135 value = attribute.value
137 if isinstance(attribute.value, models.Model):
138 attribute.value.delete()
139 value = value_class()
141 value.set_value(getattr(instance, field.name, None))
144 attribute.value = value
146 del instance.__dict__[ATTRIBUTE_REGISTRY]
149 class AttributeField(EntityProxyField):
150 def __init__(self, attribute_key=None, **kwargs):
151 self.attribute_key = attribute_key
152 super(AttributeField, self).__init__(**kwargs)
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)
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)
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.")
173 def value_class(self):
174 raise AttributeError("value_class must be defined on AttributeField subclasses.")
177 class JSONAttribute(AttributeField):
178 value_class = JSONValue
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
186 def validate_value(self, value):
189 def formfield(self, **kwargs):
192 'label': capfirst(self.verbose_name),
193 'help_text': self.help_text
195 if self.has_default():
196 defaults['initial'] = self.default
197 defaults.update(kwargs)
198 return self.field_template.formfield(**defaults)
201 class ForeignKeyAttribute(AttributeField):
202 value_class = ForeignKeyValue
204 def __init__(self, model, limit_choices_to=None, **kwargs):
205 super(ForeignKeyAttribute, self).__init__(**kwargs)
207 if limit_choices_to is None:
208 limit_choices_to = {}
209 self.limit_choices_to = limit_choices_to
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__))
215 def formfield(self, form_class=forms.ModelChoiceField, **kwargs):
217 'queryset': self.model._default_manager.complex_filter(self.limit_choices_to)
219 defaults.update(kwargs)
220 return super(ForeignKeyAttribute, self).formfield(form_class=form_class, **defaults)
222 def value_from_object(self, obj):
223 relobj = super(ForeignKeyAttribute, self).value_from_object(obj)
224 return getattr(relobj, 'pk', None)
228 """Spoof being a rel from a ForeignKey."""
231 def get_related_field(self):
232 """Again, spoof being a rel from a ForeignKey."""
233 return self.model._meta.pk
236 class ManyToManyAttribute(ForeignKeyAttribute):
237 value_class = ManyToManyValue
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__))
243 def formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
244 return super(ManyToManyAttribute, self).formfield(form_class=form_class, **kwargs)
246 def value_from_object(self, obj):
247 qs = super(ForeignKeyAttribute, self).value_from_object(obj)
249 return qs.values_list('pk', flat=True)