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.
13 numbers = models.PositiveIntegerField()
15 class ThingProxy(Thing):
16 improvised = JSONAttribute(models.BooleanField)
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
30 __all__ = ('JSONAttribute', 'ForeignKeyAttribute', 'ManyToManyAttribute')
33 ATTRIBUTE_REGISTRY = '_attribute_registry'
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
43 def actually_contribute_to_class(self, sender, **kwargs):
44 sender._entity_meta.add_proxy_field(self)
46 def contribute_to_class(self, cls, name):
47 if issubclass(cls, Entity):
48 self.name = self.attname = name
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)
54 raise FieldError('%s instances can only be declared on Entity subclasses.' % self.__class__.__name__)
56 def formfield(self, form_class=forms.CharField, **kwargs):
59 'label': capfirst(self.verbose_name),
60 'help_text': self.help_text
62 if self.has_default():
63 defaults['initial'] = self.default
64 defaults.update(kwargs)
65 return form_class(**defaults)
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)
72 def has_default(self):
73 return self.default is not NOT_PROVIDED
76 class AttributeFieldDescriptor(object):
77 def __init__(self, field):
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]
85 def __get__(self, instance, owner):
89 if self.field.name not in instance.__dict__:
90 instance.__dict__[self.field.name] = instance.attributes.get(self.field.attribute_key, None)
92 return instance.__dict__[self.field.name]
94 def __set__(self, instance, value):
96 raise AttributeError("%s must be accessed via instance" % self.field.name)
98 self.field.validate_value(value)
99 instance.__dict__[self.field.name] = value
101 registry = self.get_registry(instance)
102 registry['added'].add(self.field)
103 registry['removed'].discard(self.field)
105 def __delete__(self, instance):
106 del instance.__dict__[self.field.name]
108 registry = self.get_registry(instance)
109 registry['added'].discard(self.field)
110 registry['removed'].add(self.field)
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()
118 for field in registry['added']:
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
126 value_class = field.value_class
127 if isinstance(attribute.value, value_class):
128 value = attribute.value
130 if isinstance(attribute.value, models.Model):
131 attribute.value.delete()
132 value = value_class()
134 value.set_value(getattr(instance, field.name, None))
137 attribute.value = value
139 del instance.__dict__[ATTRIBUTE_REGISTRY]
142 class AttributeField(EntityProxyField):
143 def __init__(self, attribute_key=None, **kwargs):
144 self.attribute_key = attribute_key
145 super(AttributeField, self).__init__(**kwargs)
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)
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)
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.")
166 def value_class(self):
167 raise AttributeError("value_class must be defined on AttributeField subclasses.")
170 class JSONAttribute(AttributeField):
171 value_class = JSONValue
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
179 def validate_value(self, value):
182 def formfield(self, **kwargs):
185 'label': capfirst(self.verbose_name),
186 'help_text': self.help_text
188 if self.has_default():
189 defaults['initial'] = self.default
190 defaults.update(kwargs)
191 return self.field_template.formfield(**defaults)
194 class ForeignKeyAttribute(AttributeField):
195 value_class = ForeignKeyValue
197 def __init__(self, model, limit_choices_to=None, **kwargs):
198 super(ForeignKeyAttribute, self).__init__(**kwargs)
200 if limit_choices_to is None:
201 limit_choices_to = {}
202 self.limit_choices_to = limit_choices_to
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__))
208 def formfield(self, form_class=forms.ModelChoiceField, **kwargs):
210 'queryset': self.model._default_manager.complex_filter(self.limit_choices_to)
212 defaults.update(kwargs)
213 return super(ForeignKeyAttribute, self).formfield(form_class=form_class, **defaults)
215 def value_from_object(self, obj):
216 relobj = super(ForeignKeyAttribute, self).value_from_object(obj)
217 return getattr(relobj, 'pk', None)
220 class ManyToManyAttribute(ForeignKeyAttribute):
221 value_class = ManyToManyValue
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__))
227 def formfield(self, form_class=forms.ModelMultipleChoiceField, **kwargs):
228 return super(ManyToManyAttribute, self).formfield(form_class=form_class, **kwargs)
230 def value_from_object(self, obj):
231 qs = super(ForeignKeyAttribute, self).value_from_object(obj)
233 return qs.values_list('pk', flat=True)