django-eav2/models.py

362 lines
13 KiB
Python
Raw Normal View History

2010-09-17 12:12:18 +00:00
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 coding=utf-8
#
2010-09-17 12:14:08 +00:00
# This software is derived from EAV-Django originally written and
2010-09-17 12:12:18 +00:00
# copyrighted by Andrey Mikhaylenko <http://pypi.python.org/pypi/eav-django>
#
# This is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with EAV-Django. If not, see <http://gnu.org/licenses/>.
2010-09-24 09:48:37 +00:00
'''
.. automodule:: models
:members:
This is my models file
'''
2010-09-17 12:12:18 +00:00
import inspect
2010-09-07 10:11:09 +00:00
import re
2010-09-07 12:34:03 +00:00
from datetime import datetime
2010-09-07 10:11:09 +00:00
2010-09-23 07:38:53 +00:00
from django.db import models
2010-09-07 13:32:53 +00:00
from django.core.exceptions import ValidationError
2010-09-07 08:40:17 +00:00
from django.utils.translation import ugettext_lazy as _
2010-09-06 20:46:11 +00:00
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.conf import settings
2010-09-06 20:46:11 +00:00
2010-09-23 07:38:53 +00:00
from .validators import *
2010-09-07 13:40:50 +00:00
from .fields import EavSlugField, EavDatatypeField
2010-09-07 08:33:42 +00:00
2010-09-06 20:46:11 +00:00
2010-09-10 15:57:44 +00:00
class EnumValue(models.Model):
value = models.CharField(_(u"value"), db_index=True,
unique=True, max_length=50)
def __unicode__(self):
return self.value
class EnumGroup(models.Model):
name = models.CharField(_(u"name"), unique=True, max_length=100)
enums = models.ManyToManyField(EnumValue, verbose_name=_(u"enum group"))
def __unicode__(self):
return self.name
class Attribute(models.Model):
2010-09-07 00:14:48 +00:00
'''
The A model in E-A-V. This holds the 'concepts' along with the data type
something like:
>>> Attribute.objects.create(name='Height', datatype='float')
<Attribute: Height (Float)>
2010-09-06 20:46:11 +00:00
>>> Attribute.objects.create(name='Color', datatype='text', slug='color')
<Attribute: Color (Text)>
2010-09-07 00:14:48 +00:00
'''
2010-09-06 20:46:11 +00:00
class Meta:
ordering = ['name']
TYPE_TEXT = 'text'
TYPE_FLOAT = 'float'
TYPE_INT = 'int'
TYPE_DATE = 'date'
TYPE_BOOLEAN = 'bool'
2010-09-07 14:14:03 +00:00
TYPE_OBJECT = 'object'
2010-09-10 15:57:44 +00:00
TYPE_ENUM = 'enum'
2010-09-06 20:46:11 +00:00
DATATYPE_CHOICES = (
2010-09-07 08:33:42 +00:00
(TYPE_TEXT, _(u"Text")),
(TYPE_FLOAT, _(u"Float")),
(TYPE_INT, _(u"Integer")),
(TYPE_DATE, _(u"Date")),
(TYPE_BOOLEAN, _(u"True / False")),
2010-09-23 07:38:53 +00:00
(TYPE_OBJECT, _(u"Django Object")),
2010-09-10 15:57:44 +00:00
(TYPE_ENUM, _(u"Multiple Choice")),
2010-09-06 20:46:11 +00:00
)
2010-09-22 12:28:19 +00:00
name = models.CharField(_(u"name"), max_length=100,
help_text=_(u"User-friendly attribute name"))
2010-09-07 10:11:09 +00:00
slug = EavSlugField(_(u"slug"), max_length=50, db_index=True,
help_text=_(u"Short unique attribute label"),
unique=True)
2010-09-10 15:57:44 +00:00
description = models.CharField(_(u"description"), max_length=256,
blank=True, null=True,
help_text=_(u"Short description"))
2010-09-16 13:13:47 +00:00
enum_group = models.ForeignKey(EnumGroup, verbose_name=_(u"choice group"),
blank=True, null=True)
2010-09-10 15:57:44 +00:00
@property
def help_text(self):
return self.description
2010-09-06 20:46:11 +00:00
2010-09-07 13:40:50 +00:00
datatype = EavDatatypeField(_(u"data type"), max_length=6,
2010-09-06 20:46:11 +00:00
choices=DATATYPE_CHOICES)
created = models.DateTimeField(_(u"created"), default=datetime.now,
editable=False)
2010-09-07 12:34:03 +00:00
2010-09-07 12:44:13 +00:00
modified = models.DateTimeField(_(u"modified"), auto_now=True)
2010-09-07 12:34:03 +00:00
required = models.BooleanField(_(u"required"), default=False)
2010-09-10 15:57:44 +00:00
2010-09-23 07:38:53 +00:00
def get_validators(self):
DATATYPE_VALIDATORS = {
'text': validate_text,
'float': validate_float,
'int': validate_int,
'date': validate_date,
'bool': validate_bool,
2010-09-23 07:44:03 +00:00
'object': validate_object,
2010-09-23 07:38:53 +00:00
'enum': validate_enum,
}
validation_function = DATATYPE_VALIDATORS[self.datatype]
return [validation_function]
def validate_value(self, value):
for validator in self.get_validators():
validator(value)
2010-09-23 16:40:32 +00:00
if self.datatype == self.TYPE_ENUM:
if value not in self.enum_group.enums.all():
raise ValidationError(_(u"%(enum)s is not a valid choice "
u"for %(attr)s") % \
{'enum': value, 'attr': self})
2010-09-23 07:38:53 +00:00
2010-09-07 10:11:09 +00:00
def save(self, *args, **kwargs):
2010-09-07 11:56:35 +00:00
if not self.slug:
self.slug = EavSlugField.create_slug_from_name(self.name)
2010-09-07 10:11:09 +00:00
self.full_clean()
super(Attribute, self).save(*args, **kwargs)
2010-09-07 13:32:53 +00:00
2010-09-16 13:13:47 +00:00
def clean(self):
if self.datatype == self.TYPE_ENUM and not self.enum_group:
2010-09-16 13:13:47 +00:00
raise ValidationError(_(
u"You must set the choice group for multiple choice" \
u"attributes"))
2010-09-07 10:31:25 +00:00
2010-09-22 13:41:07 +00:00
if self.datatype != self.TYPE_ENUM and self.enum_group:
raise ValidationError(_(
u"You can only assign a choice group to multiple choice " \
u"attributes"))
def get_choices(self):
'''
Returns the avilable choices for enums.
'''
if not self.datatype == Attribute.TYPE_ENUM:
return None
return self.enum_group.enums.all()
2010-09-07 10:11:09 +00:00
2010-09-07 00:14:48 +00:00
def save_value(self, entity, value):
ct = ContentType.objects.get_for_model(entity)
try:
2010-09-22 12:28:19 +00:00
value_obj = self.value_set.get(entity_ct=ct,
entity_id=entity.pk,
attribute=self)
except Value.DoesNotExist:
2010-09-22 13:41:07 +00:00
if value == None or value == '':
2010-09-22 12:28:19 +00:00
return
value_obj = Value.objects.create(entity_ct=ct,
entity_id=entity.pk,
attribute=self)
2010-09-22 13:41:07 +00:00
if value == None or value == '':
2010-09-22 12:28:19 +00:00
value_obj.delete()
return
if value != value_obj.value:
value_obj.value = value
value_obj.save()
2010-09-06 20:46:11 +00:00
2010-09-06 20:46:11 +00:00
def __unicode__(self):
return u"%s (%s)" % (self.name, self.get_datatype_display())
class Value(models.Model):
2010-09-07 14:22:02 +00:00
'''
The V model in E-A-V. This holds the 'value' for an attribute and an
entity:
>>> from django.db import models
>>> from django.contrib.auth.models import User
2010-09-23 10:58:11 +00:00
>>> from .registry import Registry
>>> Registry.register(User)
2010-09-07 14:22:02 +00:00
>>> u = User.objects.create(username='crazy_dev_user')
>>> a = Attribute.objects.create(name='Favorite Drink', datatype='text',
2010-09-07 14:22:02 +00:00
... slug='fav_drink')
>>> Value.objects.create(entity=u, attribute=a, value_text='red bull')
<Value: crazy_dev_user - Favorite Drink: "red bull">
2010-09-07 14:22:02 +00:00
'''
2010-09-22 12:28:19 +00:00
class Meta:
unique_together = ('entity_ct', 'entity_id', 'attribute')
2010-09-07 14:14:03 +00:00
entity_ct = models.ForeignKey(ContentType, related_name='value_entities')
2010-09-07 13:59:45 +00:00
entity_id = models.IntegerField()
2010-09-23 07:38:53 +00:00
entity = generic.GenericForeignKey(ct_field='entity_ct',
fk_field='entity_id')
2010-09-06 20:46:11 +00:00
value_text = models.TextField(blank=True, null=True)
value_float = models.FloatField(blank=True, null=True)
value_int = models.IntegerField(blank=True, null=True)
value_date = models.DateTimeField(blank=True, null=True)
value_bool = models.NullBooleanField(blank=True, null=True)
value_enum = models.ForeignKey(EnumValue, blank=True, null=True,
related_name='eav_values')
generic_value_id = models.IntegerField(blank=True, null=True)
2010-09-07 14:14:03 +00:00
generic_value_ct = models.ForeignKey(ContentType, blank=True, null=True,
related_name='value_values')
value_object = generic.GenericForeignKey(ct_field='generic_value_ct',
fk_field='generic_value_id')
2010-09-06 20:46:11 +00:00
2010-09-08 12:10:47 +00:00
created = models.DateTimeField(_(u"created"), default=datetime.now)
modified = models.DateTimeField(_(u"modified"), auto_now=True)
attribute = models.ForeignKey(Attribute, db_index=True,
2010-09-16 17:19:31 +00:00
verbose_name=_(u"attribute"))
2010-09-06 20:46:11 +00:00
2010-09-07 12:44:13 +00:00
def save(self, *args, **kwargs):
self.full_clean()
super(Value, self).save(*args, **kwargs)
2010-09-07 12:44:13 +00:00
2010-09-16 13:13:47 +00:00
def clean(self):
if self.attribute.datatype == Attribute.TYPE_ENUM and \
2010-09-16 13:13:47 +00:00
self.value_enum:
if self.value_enum not in self.attribute.enum_group.enums.all():
2010-09-16 13:13:47 +00:00
raise ValidationError(_(u"%(choice)s is not a valid " \
u"choice for %s(attribute)") % \
{'choice': self.value_enum,
'attribute': self.attribute})
2010-09-23 07:38:53 +00:00
# TODO: Remove
2010-09-07 00:14:48 +00:00
def _blank(self):
"""
Set all the field to none
"""
2010-09-07 13:32:53 +00:00
for field in self._meta.fields:
if field.name.startswith('value_') and field.null == True:
setattr(self, field.name, None)
2010-09-07 00:14:48 +00:00
2010-09-06 20:46:11 +00:00
def _get_value(self):
"""
Get returns the Python object hold by this Value object.
"""
2010-09-07 08:33:42 +00:00
return getattr(self, 'value_%s' % self.attribute.datatype)
2010-09-06 20:46:11 +00:00
2010-09-06 20:46:11 +00:00
def _set_value(self, new_value):
2010-09-07 00:14:48 +00:00
self._blank()
2010-09-07 08:33:42 +00:00
setattr(self, 'value_%s' % self.attribute.datatype, new_value)
2010-09-06 20:46:11 +00:00
value = property(_get_value, _set_value)
def __unicode__(self):
2010-09-07 13:59:45 +00:00
return u"%s - %s: \"%s\"" % (self.entity, self.attribute.name, self.value)
2010-09-06 20:46:11 +00:00
2010-09-07 00:14:48 +00:00
class Entity(object):
2010-09-07 00:14:48 +00:00
def __init__(self, instance):
self.model = instance
self.ct = ContentType.objects.get_for_model(instance)
def __getattr__(self, name):
if not name.startswith('_'):
2010-09-22 12:28:19 +00:00
try:
attribute = self.get_attribute_by_slug(name)
except Attribute.DoesNotExist:
raise AttributeError(_(u"%(obj)s has no EAV attribute named " \
u"'%(attr)s'") % \
{'obj':self.model, 'attr':name})
try:
return self.get_value_by_attribute(attribute).value
except Value.DoesNotExist:
return None
2010-09-23 12:10:14 +00:00
return getattr(super(Entity, self), name)
2010-09-07 00:14:48 +00:00
2010-09-22 12:28:19 +00:00
def get_all_attributes(self):
2010-09-23 12:10:14 +00:00
return self.model._eav_config_cls.get_attributes()
2010-09-07 00:14:48 +00:00
def save(self):
2010-09-22 12:28:19 +00:00
for attribute in self.get_all_attributes():
2010-09-07 10:11:09 +00:00
if hasattr(self, attribute.slug):
attribute_value = getattr(self, attribute.slug)
2010-09-07 00:14:48 +00:00
attribute.save_value(self.model, attribute_value)
2010-09-23 07:38:53 +00:00
def validate_attributes(self):
for attribute in self.get_all_attributes():
2010-09-23 07:38:53 +00:00
value = getattr(self, attribute.slug, None)
if value is None:
if attribute.required:
raise ValidationError(_(u"%(attr)s EAV field cannot " \
u"be blank") % \
{'attr': attribute.slug})
else:
try:
attribute.validate_value(value)
except ValidationError, e:
raise ValidationError(_(u"%(attr)s EAV field %(err)s") % \
{'attr': attribute.slug,
'err': e})
2010-09-07 00:14:48 +00:00
def get_values(self):
2010-09-22 12:28:19 +00:00
'''
Get all set EAV Value objects for self.model
'''
return Value.objects.filter(entity_ct=self.ct,
2010-09-22 12:28:19 +00:00
entity_id=self.model.pk).select_related()
2010-09-08 12:10:47 +00:00
def get_all_attribute_slugs(self):
2010-09-22 12:28:19 +00:00
return self.get_all_attributes().values_list('slug', Flat=True)
2010-09-08 15:24:14 +00:00
2010-09-08 12:10:47 +00:00
def get_attribute_by_slug(self, slug):
2010-09-22 12:28:19 +00:00
return self.get_all_attributes().get(slug=slug)
2010-09-08 12:10:47 +00:00
2010-09-22 12:28:19 +00:00
def get_value_by_attribute(self, attribute):
return self.get_values().get(attribute=attribute)
2010-09-07 00:14:48 +00:00
2010-09-08 18:19:51 +00:00
def __iter__(self):
return iter(self.get_values())
2010-09-07 00:14:48 +00:00
@staticmethod
def post_save_handler(sender, *args, **kwargs):
2010-09-23 12:10:14 +00:00
instance = kwargs['instance']
entity = getattr(instance, instance._eav_config_cls.eav_attr)
2010-09-22 12:28:19 +00:00
entity.save()
@staticmethod
def pre_save_handler(sender, *args, **kwargs):
2010-09-23 12:10:14 +00:00
instance = kwargs['instance']
entity = getattr(kwargs['instance'], instance._eav_config_cls.eav_attr)
2010-09-23 07:38:53 +00:00
entity.validate_attributes()
if 'django_nose' in settings.INSTALLED_APPS:
'''
The django_nose test runner won't automatically create our Patient model
database table which is required for tests, unless we import it here.
Please, someone tell me a better way to do this.
'''
2010-09-23 16:40:32 +00:00
from .tests.models import Patient, Encounter