django-eav2/eav/models.py

677 lines
22 KiB
Python
Raw Normal View History

"""
This module defines the four concrete, non-abstract models:
* :class:`Value`
* :class:`Attribute`
* :class:`EnumValue`
* :class:`EnumGroup`
2010-09-27 13:28:52 +00:00
Along with the :class:`Entity` helper class and :class:`EAVModelMeta`
optional metaclass for each eav model class.
"""
from copy import copy
2010-09-27 13:28:52 +00:00
from django.contrib.contenttypes import fields as generic
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.base import ModelBase
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
2010-09-27 13:28:52 +00:00
from .validators import validate_decimal
from .validators import validate_enum_multi
from .validators import (
validate_text,
validate_float,
validate_int,
validate_date,
validate_bool,
validate_object,
validate_enum
)
from .exceptions import IllegalAssignmentException
from .fields import EavDatatypeField, EavSlugField
from . import register
2010-09-27 13:28:52 +00:00
class EnumValue(models.Model):
"""
*EnumValue* objects are the value 'choices' to multiple choice *TYPE_ENUM*
2020-08-12 13:29:28 +00:00
and *TYPE_ENUM_MULTI* :class:`Attribute` objects. They have only one field,
*value*, a ``CharField`` that must be unique.
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
For example::
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
yes = EnumValue.objects.create(value='Yes') # doctest: SKIP
no = EnumValue.objects.create(value='No')
unknown = EnumValue.objects.create(value='Unknown')
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
ynu = EnumGroup.objects.create(name='Yes / No / Unknown')
ynu.values.add(yes, no, unknown)
2010-09-27 13:28:52 +00:00
Attribute.objects.create(name='has fever?',
datatype=Attribute.TYPE_ENUM, enum_group=ynu)
2018-06-20 12:23:30 +00:00
# = <Attribute: has fever? (Multiple Choice)>
2010-09-27 13:28:52 +00:00
.. note::
The same *EnumValue* objects should be reused within multiple
*EnumGroups*. For example, if you have one *EnumGroup* called: *Yes /
No / Unknown* and another called *Yes / No / Not applicable*, you should
only have a total of four *EnumValues* objects, as you should have used
the same *Yes* and *No* *EnumValues* for both *EnumGroups*.
"""
value = models.CharField(_('Value'), db_index=True, max_length=100)
legacy_value = models.CharField(_('Legacy Value'), blank=True, null=True, db_index=True, max_length=100)
2010-09-27 13:28:52 +00:00
def __str__(self):
2018-06-20 12:23:30 +00:00
return '<EnumValue {}>'.format(self.value)
2010-09-27 13:28:52 +00:00
class EnumGroup(models.Model):
"""
*EnumGroup* objects have two fields - a *name* ``CharField`` and *values*,
2010-09-27 13:28:52 +00:00
a ``ManyToManyField`` to :class:`EnumValue`. :class:`Attribute` classes
2020-08-12 13:29:28 +00:00
with datatype *TYPE_ENUM* or *TYPE_ENUM_MULTI* have a ``ForeignKey``
field to *EnumGroup*.
2010-09-27 13:28:52 +00:00
See :class:`EnumValue` for an example.
"""
name = models.CharField(_('Name'), max_length = 100)
values = models.ManyToManyField(EnumValue, verbose_name = _('Enum group'))
2010-09-27 13:28:52 +00:00
2018-04-06 12:45:27 +00:00
def __str__(self):
2018-06-20 12:23:30 +00:00
return '<EnumGroup {}>'.format(self.name)
2010-09-27 13:28:52 +00:00
class Attribute(models.Model):
"""
2010-09-27 13:28:52 +00:00
Putting the **A** in *EAV*. This holds the attributes, or concepts.
Examples of possible *Attributes*: color, height, weight, number of
children, number of patients, has fever?, etc...
2010-09-27 13:28:52 +00:00
Each attribute has a name, and a description, along with a slug that must
2012-04-04 20:57:54 +00:00
be unique. If you don't provide a slug, a default slug (derived from
2010-09-27 13:28:52 +00:00
name), will be created.
The *required* field is a boolean that indicates whether this EAV attribute
2012-04-04 20:57:54 +00:00
is required for entities to which it applies. It defaults to *False*.
2010-09-27 13:28:52 +00:00
.. warning::
Just like a normal model field that is required, you will not be able
to save or create any entity object for which this attribute applies,
without first setting this EAV attribute.
2020-08-12 13:29:28 +00:00
There are 9 possible values for datatype:
2010-09-27 13:28:52 +00:00
* int (TYPE_INT)
* float (TYPE_FLOAT)
2020-08-12 13:29:28 +00:00
* decimal (TYPE_DECIMAL)
2010-09-27 13:28:52 +00:00
* text (TYPE_TEXT)
* date (TYPE_DATE)
* bool (TYPE_BOOLEAN)
* object (TYPE_OBJECT)
* enum (TYPE_ENUM)
2020-08-12 13:29:28 +00:00
* enum_multi (TYPE_ENUM_MULTI)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
Examples::
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
Attribute.objects.create(name='Height', datatype=Attribute.TYPE_INT)
# = <Attribute: Height (Integer)>
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
Attribute.objects.create(name='Color', datatype=Attribute.TYPE_TEXT)
# = <Attribute: Color (Text)>
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
yes = EnumValue.objects.create(value='yes')
no = EnumValue.objects.create(value='no')
unknown = EnumValue.objects.create(value='unknown')
ynu = EnumGroup.objects.create(name='Yes / No / Unknown')
ynu.values.add(yes, no, unknown)
2018-06-20 12:23:30 +00:00
Attribute.objects.create(name='has fever?', datatype=Attribute.TYPE_ENUM, enum_group=ynu)
# = <Attribute: has fever? (Multiple Choice)>
2010-09-27 13:28:52 +00:00
.. warning:: Once an Attribute has been used by an entity, you can not
change it's datatype.
"""
2010-09-27 13:28:52 +00:00
class Meta:
ordering = ['name']
2010-09-27 13:28:52 +00:00
TYPE_TEXT = 'text'
TYPE_FLOAT = 'float'
TYPE_DECIMAL = 'decimal'
TYPE_INT = 'int'
TYPE_DATE = 'date'
TYPE_BOOLEAN = 'bool'
TYPE_OBJECT = 'object'
TYPE_ENUM = 'enum'
TYPE_ENUM_MULTI = 'enum_multi'
2010-09-27 13:28:52 +00:00
DATATYPE_CHOICES = (
(TYPE_TEXT, _('Text')),
(TYPE_DATE, _('Date')),
(TYPE_FLOAT, _('Float')),
(TYPE_DECIMAL, _('Decimal')),
(TYPE_INT, _('Integer')),
(TYPE_BOOLEAN, _('True / False')),
(TYPE_OBJECT, _('Django Object')),
(TYPE_ENUM, _('Choice')),
(TYPE_ENUM_MULTI, _('Multiple Choice')),
2010-09-27 13:28:52 +00:00
)
2018-06-20 12:23:30 +00:00
# Core attributes
entity_ct = models.ForeignKey(
ContentType,
on_delete = models.PROTECT,
related_name = 'attribute_entities',
blank=True,
null=True,
)
entity_id = models.UUIDField(
blank=True,
null=True,
)
entity = generic.GenericForeignKey(
ct_field = 'entity_ct',
fk_field = 'entity_id'
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
datatype = EavDatatypeField(
verbose_name = _('Data Type'),
choices = DATATYPE_CHOICES,
max_length = 10
2018-06-20 12:23:30 +00:00
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
name = models.CharField(
verbose_name = _('Name'),
max_length = 100,
help_text = _('User-friendly attribute name')
)
2010-09-27 13:28:52 +00:00
"""
2018-06-20 12:23:30 +00:00
Main identifer for the attribute.
Upon creation, slug is autogenerated from the name.
(see :meth:`~eav.fields.EavSlugField.create_slug_from_name`).
"""
2018-06-20 12:23:30 +00:00
slug = EavSlugField(
verbose_name = _('Slug'),
max_length = 50,
db_index = True,
help_text = _('Short attribute label')
2018-06-20 12:23:30 +00:00
)
2010-09-27 13:28:52 +00:00
"""
2018-06-20 12:23:30 +00:00
.. warning::
This attribute should be used with caution. Setting this to *True*
means that *all* entities that *can* have this attribute will
be required to have a value for it.
"""
2018-06-20 12:23:30 +00:00
required = models.BooleanField(verbose_name = _('Required'), default = False)
enum_group = models.ForeignKey(
EnumGroup,
verbose_name = _('Choice Group'),
on_delete = models.PROTECT,
blank = True,
null = True
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
description = models.CharField(
verbose_name = _('Description'),
max_length = 256,
blank = True,
null = True,
help_text = _('Short description')
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
# Useful meta-information
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
display_order = models.PositiveIntegerField(
verbose_name = _('Display order'),
default = 1
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
modified = models.DateTimeField(
verbose_name = _('Modified'),
auto_now = True
)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
created = models.DateTimeField(
verbose_name = _('Created'),
default = timezone.now,
editable = False
)
2018-06-20 12:23:30 +00:00
@property
def help_text(self):
return self.description
2010-09-30 09:43:26 +00:00
2010-09-27 13:28:52 +00:00
def get_validators(self):
"""
2010-09-27 13:28:52 +00:00
Returns the appropriate validator function from :mod:`~eav.validators`
as a list (of length one) for the datatype.
.. note::
The reason it returns it as a list, is eventually we may want this
method to look elsewhere for additional attribute specific
validators to return as well as the default, built-in one.
"""
2010-09-27 13:28:52 +00:00
DATATYPE_VALIDATORS = {
'text': validate_text,
'float': validate_float,
'decimal': validate_decimal,
'int': validate_int,
'date': validate_date,
'bool': validate_bool,
'object': validate_object,
'enum': validate_enum,
'enum_multi': validate_enum_multi,
2010-09-27 13:28:52 +00:00
}
2018-04-06 11:59:51 +00:00
2018-06-20 12:23:30 +00:00
return [DATATYPE_VALIDATORS[self.datatype]]
2010-09-27 13:28:52 +00:00
def validate_value(self, value):
"""
2010-09-27 13:28:52 +00:00
Check *value* against the validators returned by
:meth:`get_validators` for this attribute.
"""
2010-09-27 13:28:52 +00:00
for validator in self.get_validators():
validator(value)
2018-06-20 12:23:30 +00:00
2010-09-27 13:28:52 +00:00
if self.datatype == self.TYPE_ENUM:
if isinstance(value, EnumValue):
value = value.value
if not self.enum_group.values.filter(value=value).exists():
2018-06-20 12:23:30 +00:00
raise ValidationError(
2020-08-12 13:29:28 +00:00
_('{val} is not a valid choice for {attr}').format(val = value, attr = self)
)
if self.datatype == self.TYPE_ENUM_MULTI:
2020-08-17 06:11:25 +00:00
value = [v.value if isinstance(v, EnumValue) else v for v in value.all()]
2020-08-12 13:29:28 +00:00
if self.enum_group.values.filter(value__in=value).count() != len(value):
raise ValidationError(
_('{val} is not a valid choice for {attr}').format(val = value, attr = self)
2018-06-20 12:23:30 +00:00
)
2010-09-27 13:28:52 +00:00
def save(self, *args, **kwargs):
"""
2018-06-20 12:23:30 +00:00
Saves the Attribute and auto-generates a slug field
if one wasn't provided.
"""
2010-09-27 13:28:52 +00:00
if not self.slug:
self.slug = EavSlugField.create_slug_from_name(self.name)
2018-06-20 12:23:30 +00:00
2010-09-27 13:28:52 +00:00
self.full_clean()
super(Attribute, self).save(*args, **kwargs)
def clean(self):
"""
Validates the attribute. Will raise ``ValidationError`` if the
2020-08-12 13:29:28 +00:00
attribute's datatype is *TYPE_ENUM* or *TYPE_ENUM_MULTI* and
enum_group is not set, or if the attribute is not *TYPE_ENUM*
or *TYPE_ENUM_MULTI* and the enum group is set.
"""
2020-08-12 13:29:28 +00:00
if self.datatype in (self.TYPE_ENUM, self.TYPE_ENUM_MULTI) and not self.enum_group:
2018-06-20 12:23:30 +00:00
raise ValidationError(
_('You must set the choice group for multiple choice attributes')
)
2010-09-27 13:28:52 +00:00
2020-08-12 13:29:28 +00:00
if self.datatype not in (self.TYPE_ENUM, self.TYPE_ENUM_MULTI) and self.enum_group:
2018-06-20 12:23:30 +00:00
raise ValidationError(
_('You can only assign a choice group to multiple choice attributes')
)
2010-09-27 13:28:52 +00:00
def get_choices(self):
"""
2010-09-27 13:28:52 +00:00
Returns a query set of :class:`EnumValue` objects for this attribute.
2020-08-12 13:29:28 +00:00
Returns None if the datatype of this attribute is not *TYPE_ENUM* or
*TYPE_ENUM_MULTI*.
"""
2020-08-12 13:29:28 +00:00
return self.enum_group.values.all() if self.datatype in (self.TYPE_ENUM, self.TYPE_ENUM_MULTI) else None
2010-09-27 13:28:52 +00:00
def save_value(self, entity, value):
"""
2018-06-20 12:23:30 +00:00
Called with *entity*, any Django object registered with eav, and
2010-09-27 13:28:52 +00:00
*value*, the :class:`Value` this attribute for *entity* should
be set to.
If a :class:`Value` object for this *entity* and attribute doesn't
exist, one will be created.
.. note::
If *value* is None and a :class:`Value` object exists for this
2018-06-20 12:23:30 +00:00
Attribute and *entity*, it will delete that :class:`Value` object.
"""
2010-09-27 13:28:52 +00:00
ct = ContentType.objects.get_for_model(entity)
2018-06-20 12:23:30 +00:00
2010-09-27 13:28:52 +00:00
try:
2018-06-20 12:23:30 +00:00
value_obj = self.value_set.get(
entity_ct = ct,
entity_id = entity.pk,
attribute = self
)
2010-09-27 13:28:52 +00:00
except Value.DoesNotExist:
2020-08-12 13:29:28 +00:00
if value in (None, '', []):
2010-09-27 13:28:52 +00:00
return
2018-06-20 12:23:30 +00:00
value_obj = Value.objects.create(
entity_ct = ct,
entity_id = entity.pk,
attribute = self
)
2020-08-12 13:29:28 +00:00
if value in (None, '', []):
2010-09-27 13:28:52 +00:00
value_obj.delete()
return
if value != value_obj.value:
2020-08-12 13:29:28 +00:00
if self.datatype == self.TYPE_ENUM_MULTI:
value_obj.value.clear()
value_obj.value.add(*value)
else:
value_obj.value = value
value_obj.save()
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
def __str__(self):
return '{} ({})'.format(self.name, self.get_datatype_display())
2010-09-27 13:28:52 +00:00
class Value(models.Model):
"""
2010-09-27 13:28:52 +00:00
Putting the **V** in *EAV*. This model stores the value for one particular
:class:`Attribute` for some entity.
As with most EAV implementations, most of the columns of this model will
be blank, as onle one *value_* field will be used.
2018-06-20 12:23:30 +00:00
Example::
import eav
from django.contrib.auth.models import User
eav.register(User)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
u = User.objects.create(username='crazy_dev_user')
a = Attribute.objects.create(name='Fav Drink', datatype='text')
Value.objects.create(entity = u, attribute = a, value_text = 'red bull')
# = <Value: crazy_dev_user - Fav Drink: "red bull">
"""
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
entity_ct = models.ForeignKey(
ContentType,
on_delete = models.PROTECT,
related_name = 'value_entities'
)
2010-09-27 13:28:52 +00:00
entity_id = models.IntegerField()
2018-06-20 12:23:30 +00:00
entity = generic.GenericForeignKey(ct_field = 'entity_ct', fk_field = 'entity_id')
value_text = models.TextField(blank = True, null = True)
value_float = models.FloatField(blank = True, null = True)
value_decimal = models.DecimalField(blank = True, null = True, max_digits = 14, decimal_places = 2)
value_int = models.IntegerField(blank = True, null = True)
value_date = models.DateTimeField(blank = True, null = True)
value_bool = models.NullBooleanField(blank = True, null = True)
2018-06-20 12:23:30 +00:00
value_enum = models.ForeignKey(
EnumValue,
blank = True,
null = True,
on_delete = models.PROTECT,
related_name = 'eav_values'
)
2010-09-27 13:28:52 +00:00
value_enum_multi = models.ManyToManyField(
EnumValue,
related_name = 'eav_multi_values'
)
2010-09-27 13:28:52 +00:00
generic_value_id = models.IntegerField(blank=True, null=True)
2018-06-20 12:23:30 +00:00
generic_value_ct = models.ForeignKey(
ContentType,
blank = True,
null = True,
on_delete = models.PROTECT,
related_name ='value_values'
)
value_object = generic.GenericForeignKey(
ct_field = 'generic_value_ct',
fk_field = 'generic_value_id'
)
created = models.DateTimeField(_('Created'), default = timezone.now)
modified = models.DateTimeField(_('Modified'), auto_now = True)
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
attribute = models.ForeignKey(
Attribute,
db_index = True,
on_delete = models.PROTECT,
verbose_name = _('Attribute')
2018-06-20 12:23:30 +00:00
)
2010-09-27 13:28:52 +00:00
def save(self, *args, **kwargs):
"""
2018-06-20 12:23:30 +00:00
Validate and save this value.
"""
2010-09-27 13:28:52 +00:00
self.full_clean()
super(Value, self).save(*args, **kwargs)
def _get_value(self):
"""
2010-09-27 13:28:52 +00:00
Return the python object this value is holding
"""
2010-09-27 13:28:52 +00:00
return getattr(self, 'value_%s' % self.attribute.datatype)
def _set_value(self, new_value):
"""
2010-09-27 13:28:52 +00:00
Set the object this value is holding
"""
2010-09-27 13:28:52 +00:00
setattr(self, 'value_%s' % self.attribute.datatype, new_value)
value = property(_get_value, _set_value)
def __str__(self):
return '{}: "{}" ({})'.format(self.attribute.name, self.value, self.entity)
def __repr__(self):
return '{}: "{}" ({})'.format(self.attribute.name, self.value, self.entity.pk)
2010-09-27 13:28:52 +00:00
class Entity(object):
"""
2018-06-20 12:23:30 +00:00
The helper class that will be attached to any entity
registered with eav.
"""
2018-06-20 12:23:30 +00:00
@staticmethod
def pre_save_handler(sender, *args, **kwargs):
"""
Pre save handler attached to self.instance. Called before the
2018-06-20 12:23:30 +00:00
model instance we are attached to is saved. This allows us to call
:meth:`validate_attributes` before the entity is saved.
"""
2018-06-20 12:23:30 +00:00
instance = kwargs['instance']
entity = getattr(kwargs['instance'], instance._eav_config_cls.eav_attr)
entity.validate_attributes()
2010-09-27 13:28:52 +00:00
@staticmethod
def post_save_handler(sender, *args, **kwargs):
"""
Post save handler attached to self.instance. Calls :meth:`save` when
the model instance we are attached to is saved.
"""
instance = kwargs['instance']
entity = getattr(instance, instance._eav_config_cls.eav_attr)
entity.save()
2010-09-27 13:28:52 +00:00
def __init__(self, instance):
"""
Set self.instance equal to the instance of the model that we're attached
2018-06-20 12:23:30 +00:00
to. Also, store the content type of that instance.
"""
self.instance = instance
2010-09-27 13:28:52 +00:00
self.ct = ContentType.objects.get_for_model(instance)
def __getattr__(self, name):
"""
2018-06-20 12:23:30 +00:00
Tha magic getattr helper. This is called whenever user invokes::
instance.<attribute>
2010-09-27 13:28:52 +00:00
Checks if *name* is a valid slug for attributes available to this
instances. If it is, tries to lookup the :class:`Value` with that
attribute slug. If there is one, it returns the value of the
class:`Value` object, otherwise it hasn't been set, so it returns
None.
"""
2010-09-27 13:28:52 +00:00
if not name.startswith('_'):
try:
attribute = self.get_attribute_by_slug(name)
except Attribute.DoesNotExist:
2018-06-20 12:23:30 +00:00
raise AttributeError(
_('%(obj)s has no EAV attribute named %(attr)s')
% dict(obj = self.instance, attr = name)
2018-06-20 12:23:30 +00:00
)
2010-09-27 13:28:52 +00:00
try:
return self.get_value_by_attribute(attribute).value
except Value.DoesNotExist:
return None
2018-06-20 12:23:30 +00:00
2010-09-27 13:28:52 +00:00
return getattr(super(Entity, self), name)
def get_all_attributes(self):
"""
2010-09-27 13:28:52 +00:00
Return a query set of all :class:`Attribute` objects that can be set
for this entity.
"""
return self.instance._eav_config_cls.get_attributes(self.instance).order_by('display_order')
2010-09-27 13:28:52 +00:00
def _hasattr(self, attribute_slug):
"""
2018-06-20 12:23:30 +00:00
Since we override __getattr__ with a backdown to the database, this
exists as a way of checking whether a user has set a real attribute on
ourselves, without going to the db if not.
"""
return attribute_slug in self.__dict__
def _getattr(self, attribute_slug):
"""
2018-06-20 12:23:30 +00:00
Since we override __getattr__ with a backdown to the database, this
exists as a way of getting the value a user set for one of our
attributes, without going to the db to check.
"""
return self.__dict__[attribute_slug]
2010-09-27 13:28:52 +00:00
def save(self):
"""
2010-09-27 13:28:52 +00:00
Saves all the EAV values that have been set on this entity.
"""
2010-09-27 13:28:52 +00:00
for attribute in self.get_all_attributes():
if self._hasattr(attribute.slug):
attribute_value = self._getattr(attribute.slug)
2020-08-19 07:49:44 +00:00
if attribute.datatype == Attribute.TYPE_ENUM and not isinstance(attribute_value, EnumValue) and attribute_value:
attribute_value = EnumValue.objects.get(value=attribute_value)
2020-08-12 13:29:28 +00:00
if attribute.datatype == Attribute.TYPE_ENUM_MULTI:
attribute_value = [
2020-09-06 08:38:49 +00:00
EnumValue.objects.get(value=v) if not isinstance(v, EnumValue) else v
2020-08-12 13:29:28 +00:00
for v in attribute_value
]
attribute.save_value(self.instance, attribute_value)
2010-09-27 13:28:52 +00:00
def validate_attributes(self):
"""
2010-09-27 13:28:52 +00:00
Called before :meth:`save`, first validate all the entity values to
make sure they can be created / saved cleanly.
Raises ``ValidationError`` if they can't be.
"""
values_dict = self.get_values_dict()
2010-09-27 13:28:52 +00:00
for attribute in self.get_all_attributes():
value = None
2018-06-20 12:23:30 +00:00
# Value was assigned to this instance.
if self._hasattr(attribute.slug):
value = self._getattr(attribute.slug)
values_dict.pop(attribute.slug, None)
# Otherwise try pre-loaded from DB.
else:
value = values_dict.pop(attribute.slug, None)
2010-09-27 13:28:52 +00:00
if value is None:
if attribute.required:
raise ValidationError(
_('{} EAV field cannot be blank'.format(attribute.slug))
)
2010-09-27 13:28:52 +00:00
else:
try:
attribute.validate_value(value)
2015-06-23 11:56:03 +00:00
except ValidationError as e:
2018-06-20 12:23:30 +00:00
raise ValidationError(
_('%(attr)s EAV field %(err)s')
% dict(attr = attribute.slug, err = e)
)
illegal = values_dict or (
self.get_object_attributes() - self.get_all_attribute_slugs())
2018-06-20 12:23:30 +00:00
if illegal:
raise IllegalAssignmentException(
'Instance of the class {} cannot have values for attributes: {}.'
.format(self.instance.__class__, ', '.join(illegal))
)
def get_values_dict(self):
return {v.attribute.slug: v.value for v in self.get_values()}
2010-09-27 13:28:52 +00:00
def get_values(self):
"""
Get all set :class:`Value` objects for self.instance
"""
2018-06-20 12:23:30 +00:00
return Value.objects.filter(
entity_ct = self.ct,
entity_id = self.instance.pk
2018-06-20 12:23:30 +00:00
).select_related()
2010-09-27 13:28:52 +00:00
def get_all_attribute_slugs(self):
"""
2010-09-27 13:28:52 +00:00
Returns a list of slugs for all attributes available to this entity.
"""
return set(self.get_all_attributes().values_list('slug', flat=True))
2010-09-27 13:28:52 +00:00
def get_attribute_by_slug(self, slug):
"""
2018-06-20 12:23:30 +00:00
Returns a single :class:`Attribute` with *slug*.
"""
2010-09-27 13:28:52 +00:00
return self.get_all_attributes().get(slug=slug)
def get_value_by_attribute(self, attribute):
"""
2018-06-20 12:23:30 +00:00
Returns a single :class:`Value` for *attribute*.
"""
2010-09-27 13:28:52 +00:00
return self.get_values().get(attribute=attribute)
def get_object_attributes(self):
"""
Returns entity instance attributes, except for
``instance`` and ``ct`` which are used internally.
"""
return set(copy(self.__dict__).keys()) - set(['instance', 'ct'])
2010-09-27 13:28:52 +00:00
def __iter__(self):
"""
2018-06-20 12:23:30 +00:00
Iterate over set eav values. This would allow you to do::
2010-09-27 13:28:52 +00:00
2018-06-20 12:23:30 +00:00
for i in m.eav: print(i)
"""
2010-09-27 13:28:52 +00:00
return iter(self.get_values())
class EAVModelMeta(ModelBase):
def __new__(cls, name, bases, namespace, **kwds):
result = super(EAVModelMeta, cls).__new__(cls, name, bases, dict(namespace))
register(result)
return result