Docstrings

models

This module defines the four concrete, non-abstract models:

Along with the Entity helper class.

Classes

class eav.models.Attribute(*args, **kwargs)

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...

Each attribute has a name, and a description, along with a slug that must be unique. If you don’t provide a slug, a default slug (derrived from name), will be created.

The required field is a boolean that indicates whether this EAV attribute is required for entitys to which it applies. It defaults to False.

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.

There are 7 possible values for datatype:

  • int (TYPE_INT)
  • float (TYPE_FLOAT)
  • text (TYPE_TEXT)
  • date (TYPE_DATE)
  • bool (TYPE_BOOLEAN)
  • object (TYPE_OBJECT)
  • enum (TYPE_ENUM)

Examples:

>>> Attribute.objects.create(name='Height', datatype=Attribute.TYPE_INT)
<Attribute: Height (Float)>
>>> Attribute.objects.create(name='Color', datatype=Attribute.TYPE_TEXT)
<Attribute: Color (Text)>
>>> yes = EnumValue.objects.create(value='yes')
>>> no = EnumValue.objects.create(value='no')
>>> unkown = EnumValue.objects.create(value='unkown')
>>> ynu = EnumGroup.objects.create(name='Yes / No / Unkown')
>>> ynu.enums.add(yes, no, unkown)
>>> Atrribute.objects.create(name='Has Fever?',
...                          datatype=Attribute.TYPE_ENUM,
...                          enum_group=ynu)
<Attribute: Has Fever? (Multiple Choice)>

Warning

Once an Attribute has been used by an entity, you can not change it’s datatype.

clean()
Validates the attribute. Will raise ValidationError if the attribute’s datatype is TYPE_ENUM and enum_group is not set, or if the attribute is not TYPE_ENUM and the enum group is set.
get_choices()
Returns a query set of EnumValue objects for this attribute. Returns None if the datatype of this attribute is not TYPE_ENUM.
get_validators()

Returns the appropriate validator function from 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.

save(*args, **kwargs)
Saves the Attribute and auto-generates a slug field if one wasn’t provided.
save_value(entity, value)

Called with entity, any django object registered with eav, and value, the Value this attribute for entity should be set to.

If a Value object for this entity and attribute doesn’t exist, one will be created.

Note

If value is None and a Value object exists for this
Attribute and entity, it will delete that Value object.
validate_value(value)
Check value against the validators returned by get_validators() for this attribute.
class eav.models.Entity(instance)

The helper class that will be attached to any entity registered with eav.

get_all_attribute_slugs()
Returns a list of slugs for all attributes available to this entity.
get_all_attributes()
Return a query set of all Attribute objects that can be set for this entity.
get_attribute_by_slug(slug)
Returns a single Attribute with slug
get_value_by_attribute(attribute)
Returns a single Value for attribute
get_values()
Get all set Value objects for self.model
static post_save_handler(sender, *args, **kwargs)
Post save handler attached to self.model. Calls save() when the model instance we are attached to is saved.
static pre_save_handler(sender, *args, **kwargs)
Pre save handler attached to self.model. Called before the model instance we are attached to is saved. This allows us to call validate_attributes() before the entity is saved.
save()
Saves all the EAV values that have been set on this entity.
validate_attributes()

Called before save(), first validate all the entity values to make sure they can be created / saved cleanly.

Raise ValidationError if they can’t be.

class eav.models.EnumGroup(*args, **kwargs)

EnumGroup objects have two fields- a name CharField and enums, a ManyToManyField to EnumValue. Attribute classes with datatype TYPE_ENUM have a ForeignKey field to EnumGroup.

See EnumValue for an example.

class eav.models.EnumValue(*args, **kwargs)

EnumValue objects are the value ‘choices’ to multiple choice TYPE_ENUM Attribute objects.

They have only one field, value, a``CharField`` that must be unique.

For example:

>>> yes = EnumValue.objects.create(value='yes')
>>> no = EnumValue.objects.create(value='no')
>>> unkown = EnumValue.objects.create(value='unkown')
>>> ynu = EnumGroup.objects.create(name='Yes / No / Unkown')
>>> ynu.enums.add(yes, no, unkown)
>>> Atrribute.objects.create(name='Has Fever?',
...                          datatype=Attribute.TYPE_ENUM,
...                          enum_group=ynu)

Note

The same EnumValue objects should be reused within multiple EnumGroups. For example, if you have one EnumGroup called: Yes / No / Unkown 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.

class eav.models.Value(*args, **kwargs)

Putting the V in EAV. This model stores the value for one particular 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.

Example:

>>> import eav
>>> from django.contrib.auth.models import User
>>> eav.register(User)
>>> u = User.objects.create(username='crazy_dev_user')
>>> a = Attribute.objects.create(name='Favorite Drink', datatype='text',
... slug='fav_drink')
>>> Value.objects.create(entity=u, attribute=a, value_text='red bull')
<Value: crazy_dev_user - Favorite Drink: "red bull">
clean()
Raises ValidationError if this value’s attribute is TYPE_ENUM and value_enum is not a valid choice for this value’s attribute.
entity
Provides a generic relation to any object through content-type/object-id fields.
save(*args, **kwargs)
Validate and save this value
value
Return the python object this value is holding
value_object
Provides a generic relation to any object through content-type/object-id fields.

validators

This module contains a validator for each Attribute datatype.

A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet some criteria. (see django validators)

These validators are called by the validate_value() method in the Attribute model.

Functions

eav.validators.validate_bool(value)
Raises ValidationError unless value type is bool
eav.validators.validate_date(value)
Raises ValidationError unless value is an instance of datetime or date
eav.validators.validate_enum(value)
Raises ValidationError unless value is a saved EnumValue model instance.
eav.validators.validate_float(value)
Raises ValidationError unless value can be cast as a float
eav.validators.validate_int(value)
Raises ValidationError unless value can be cast as an int
eav.validators.validate_object(value)
Raises ValidationError unless value is a saved django model instance.
eav.validators.validate_text(value)
Raises ValidationError unless value type is str or unicode

fields

Contains two custom fields:

Classes

class eav.fields.EavDatatypeField(*args, **kwargs)

The datatype field used by Attribute

validate(value, instance)
Raise ValidationError if they try to change the datatype of an Attribute that is already used by Value objects.
class eav.fields.EavSlugField(*args, **kwargs)

The slug field used by Attribute

static create_slug_from_name(name)
Creates a slug based on the name
validate(value, instance)
Slugs are used to convert the Python attribute name to a database lookup and vice versa. We need it to be a valid Python identifier. We don’t want it to start with a ‘_’, underscore will be used var variables we don’t want to be saved in db.

forms

The forms used for admin integration

Classes

class eav.forms.BaseDynamicEntityForm(data=None, *args, **kwargs)

ModelForm for entity with support for EAV attributes. Form fields are created on the fly depending on Schema defined for given entity instance. If no schema is defined (i.e. the entity instance has not been saved yet), only static fields are used. However, on form validation the schema will be retrieved and EAV fields dynamically added to the form, so when the validation is actually done, all EAV fields are present in it (unless Rubric is not defined).

save(commit=True)

Saves this form‘s cleaned_data into model instance self.instance and related EAV attributes.

Returns instance.

managers

Contains the custom manager used by entities registered with eav.

Functions and Classes

class eav.managers.EntityManager

Our custom manager, overriding models.Manager

create(**kwargs)
Parse eav attributes out of kwargs, then try to create and save the object, then assign and save it’s eav attributes.
exclude(*args, **kwargs)
Pass args and kwargs through eav_filter(), then pass to the models.Manager exclude method.
filter(*args, **kwargs)
Pass args and kwargs through eav_filter(), then pass to the models.Manager filter method.
get(*args, **kwargs)
Pass args and kwargs through eav_filter(), then pass to the models.Manager get method.
get_or_create(**kwargs)
Reproduces the behavior of get_or_create, eav friendly.
eav.managers.eav_filter(func)
Decorator used to wrap filter and exlclude methods. Passes args through expand_q_filters and kwargs through expand_eav_filter. Returns the called function (filter or exclude)
eav.managers.expand_eav_filter(model_cls, key, value)

Accepts a model class and a key, value. Recurisively replaces any eav filter with a subquery.

For example:

key = 'eav__height'
value = 5

Would return:

key = 'eav_values__in'
value = Values.objects.filter(value_int=5, attribute__slug='height')
eav.managers.expand_q_filters(q, root_cls)
Takes a Q object and a model class. Recursivley passes each filter / value in the Q object tree leaf nodes through expand_eav_filter

registry

This contains the registry classes

Classes

class eav.registry.EavConfig

The default EevConfig class used if it is not overriden on registration. This is where all the default eav attribute names are defined.

classmethod get_attributes()
By default, all Attribute object apply to an entity, unless you provide a custom EavConfig class overriding this.
class eav.registry.Registry(model_cls)

Handles registration through the register() and unregister() methods.

static attach_eav_attr(sender, *args, **kwargs)
Attache EAV Entity toolkit to an instance after init.
static register(model_cls, config_cls=None)

Registers model_cls with eav. You can pass an optional config_cls to override the EavConfig defaults.

Note

Multiple registrations for the same entity are harmlessly ignored.

static unregister(model_cls)

Unregisters model_cls with eav.

Note

Unregistering a class not already registered is harmlessly ignored.

Table Of Contents

Previous topic

django-eav

This Page