Database

development area

A plethora, a cornucopia, a totally ridiculous number of models, fields, and other resources that may be used as a starting point for your database.

Version: 0.4.0-d

Database Modules Overview

Name

Version

Stage

Maintainer

archived

0.10.0-d

development

Shawn Davis <shawn@superdjango.com>

audit

0.11.0-d

development

Shawn Davis <shawn@superdjango.com>

calculated

0.6.0-p

planning

Shawn Davis <shawn@superdjango.com>

completed

0.11.0-d

development

Shawn Davis <shawn@superdjango.com>

datetime

0.8.0-d

development

Shawn Davis <shawn@superdjango.com>

default

0.6.0-x

experimental

Shawn Davis <shawn@superdjango.com>

displayed

0.4.0-a

alpha

Shawn Davis <shawn@superdjango.com>

eav

0.6.0-x

experimental

Shawn Davis <shawn@superdjango.com>

expiration

0.7.0-p

planning

Shawn Davis <shawn@superdjango.com>

history

0.7.0-p

planning

Shawn Davis <shawn@superdjango.com>

locked

0.7.1-p

planning

Shawn Davis <shawn@superdjango.com>

lookups

0.9.0-d

development

Shawn Davis <shawn@superdjango.com>

owned

0.12.1-d

development

Shawn Davis <shawn@superdjango.com>

parent

0.7.0-x

experimental

Shawn Davis <shawn@superdjango.com>

polymorphic

0.4.0-x

experimental

Shawn Davis <shawn@superdjango.com>

primary

0.7.0-x

experimental

Shawn Davis <shawn@superdjango.com>

published

0.10.0-d

development

Shawn Davis <shawn@superdjango.com>

random

0.6.0-x

experimental

Shawn Davis <shawn@superdjango.com>

resolved

0.3.0-d

development

Shawn Davis <shawn@superdjango.com>

reviewed

0.3.0-d

development

Shawn Davis <shawn@superdjango.com>

revised

0.2.0-x

experimental

Shawn Davis <shawn@superdjango.com>

slug

0.4.0-x

experimental

Shawn Davis <shawn@superdjango.com>

sorted

0.7.0-x

experimental

Shawn Davis <shawn@superdjango.com>

timed

0.6.0-x

experimental

Shawn Davis <shawn@superdjango.com>

trashed

0.6.1-x

experimental

Shawn Davis <shawn@superdjango.com>

utils

0.1.0-x

experimental

Shawn Davis <shawn@superdjango.com>

The resources provided by SuperDjango DB general consist of abstract models that may be used for various common (and some not so common) purposes.

Note

SuperDjango DB does not (and will never) provide concrete models.

Archived Models

development library

Provides support for a simple archive workflow.

Component Reference: Archived Models

admin

class superdjango.db.archived.admin.BaseArchivedAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the ArchivedModel.

get_actions(request)[source]

Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

mark_archived(request, queryset)[source]

Mark a set of records as archived.

mark_unarchived(request, queryset)[source]

Mark a set of records as unarchived.

save_model(request, obj, form, change)[source]

Given a model instance save it to the database.

filters

Audit filters may be used in the Django Admin to create list filters using the full name of the user.

class superdjango.db.archived.filters.ArchivedByListFilter(request, params, model, model_admin)[source]

Bases: django.contrib.admin.filters.SimpleListFilter

Filter for archived_by.

Order By

Ordering for the lookup defaults to USERNAME_FIELD. You can change this by setting SUPERDJANGO_ORDER_USERS_BY in your settings.py file.

lookups(request, model_admin)[source]

Must be overridden to return a list of tuples (value, verbose value)

queryset(request, queryset)[source]

Return the filtered queryset.

managers

class superdjango.db.archived.managers.ArchivedManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Automatically filters out archived records.

archived()[source]

Specifically select archived records.

unarchived()[source]

Specifically select unarchived records.

models

class superdjango.db.archived.models.ArchivedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Supports records that may be archived.

Fields

  • archived_by

  • archived_dt

  • is_archived

Proper Name

The archived_by_name property is also provided which attempts to return the full name of the user.

Methods

  • mark_archived()

  • mark_unarchived()

Parameters
  • cached_archived_by_name (CharField) – The name of the person that archived the record.

  • archived_by_id (ForeignKey) – The user that archived the record.

  • archived_dt (DateTimeField) – Date and time the record was archived.

  • is_archived (BooleanField) – Indicates the record is archived.

property archived_by_name

Get the name of the user that archived the record.

Return type

str | None

mark_archived(user, audit=True, commit=True)[source]

Mark the record as archived.

Parameters
  • user (AUTH_USER_MODEL) – The user marking the record as archived.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Whether to save immediately.

Note

Mark archived changes the record only if archived_dt is None. This prevents updating the user or date/time if mark_archived() is called more than once.

mark_unarchived(user, audit=True, commit=True)[source]

Mark the record as un-archived.

Parameters
  • user (AUTH_USER_MODEL) – The user marking the record as un-archived.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Whether to save immediately.

Audit Models

development library

Adds support for added by/modified by/viewed by (and added/modified/viewed date/time) to a model.

Component Reference: Audit Models

mixins

class superdjango.db.audit.mixins.AuditMixin(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base for other abstract auditing models.

The class serves two purposes:

  1. Provide a centralized audit() method that child classes may call to save audit data.

  2. Act as a flag for the is_audit_model() function to indicate the presence of audit functionality.

audit(user, commit=True)[source]

Save the model along with audit data.

Parameters
  • user (AUTH_USER_MODEL) – The user saving the record.

  • commit (bool) – Whether to save immediately.

models

class superdjango.db.audit.models.AddedByModel(*args, **kwargs)[source]

Bases: superdjango.db.audit.mixins.AuditMixin, django.db.models.base.Model

Tracks the user that added a record as well as the date and time the record was created.

Fields

This class will add the following fields:

  • added_by The user that added the record.

  • added_dt The date and time the record was added.

Proper Name

The added_by_name property is also provided which attempts to return the full name of the user.

Implementation

class Project(AddedByModel):

    # ...

    class Meta:
        get_latest_by = "added_dt"
        ordering = ["-added_dt"]
Parameters
  • added_by_id (ForeignKey) – Added by

  • added_dt (AutoNowAddDateTimeField) – Date and time the record was created.

property added_by_name

Get the full name or user name of the user that added the record.

Return type

str

audit(user, commit=True)[source]

Check for added_by_id just in case the primary key is being managed at run time.

A RelatedObjectDoesNotExist error will be thrown if we just look for added_by, so the simplest thing to do appears to be checking for the primary key instead.

class superdjango.db.audit.models.ModifiedByModel(*args, **kwargs)[source]

Bases: superdjango.db.audit.mixins.AuditMixin

Tracks the user that last updated a record as well as the date and time of the last update.

Fields

This class will add the following fields:

  • modified_by The user that modified record.

  • modified_dt The date and time the modified was added.

Proper Name

The modified_by_name property is also provided which attempts to return the full name of the user.

Implementation

class MyModel(ModifiedByModel):

    # ...

    class Meta:
        ordering = ["modified_dt"]
Parameters
  • modified_by_id (ForeignKey) – Modified by

  • modified_dt (AutoNowDateTimeField) – Date and time the record was last modified.

audit(user, commit=True)[source]

Always sets modified_by to the given user.

property modified_by_name

Get the full name or user name of the user that last modified the record.

Return type

str

class superdjango.db.audit.models.ViewedByModel(*args, **kwargs)[source]

Bases: superdjango.db.audit.mixins.AuditMixin

Tracks the user that view a record as well as the date and time the record was last viewed.

Fields

This class will add the following fields:

  • viewed_by The user that viewed record.

  • viewed_dt The date and time the record was last viewed.

Proper Name

The viewed_by_name property is also provided which attempts to return the full name of the user.

Implementation

class MedicalRecord(ViewedByModel):
    # ...
Parameters
  • viewed_by_id (ForeignKey) – Viewed by

  • viewed_dt (DateTimeField) – Date and time the record was last viewed.

audit(user, commit=True)[source]

Update viewed fields.

Important

This method makes calls to super() which may also trigger the update of other fields if the model also extends AddedByModel or ModifiedByModel. See mark_viewed() if you just want to update the viewed_by and viewed_dt fields.

mark_unviewed(commit=True)[source]

Mark the record as “un-viewed”, removing the last viewed data.

Parameters

commit (bool) – Indicates the record should be saved after updating the field.

mark_viewed(user, commit=True)[source]

Mark the record as viewed.

Parameters
  • user (AUTH_USER_MODEL) – The user that reviewed the record.

  • commit (bool) – Indicates the record should be saved after updating the field.

property viewed_by_name

Get the full name or user name of the user that last viewed the record.

Return type

str

admin

class superdjango.db.audit.admin.BaseAuditModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the AuditMixin.

save_model(request, obj, form, change)[source]

Use the audit() method of the instance to save audit data before continuing with saving the model.

filters

Audit filters may be used in the Django Admin to create list filters using the full name of the user.

class superdjango.db.audit.filters.AddedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for added_by.

class superdjango.db.audit.filters.BaseAuditListFilter(request, params, model, model_admin)[source]

Bases: django.contrib.admin.filters.SimpleListFilter

Base class for creating list filters based on user audit fields.

Order By

Ordering for the lookup defaults to USERNAME_FIELD. You can change this by setting SUPERDJANGO_ORDER_USERS_BY in your settings.py file.

Implementation

When extending, set the parameter_name to the name of the audit field.

lookups(request, model_admin)[source]

Must be overridden to return a list of tuples (value, verbose value)

queryset(request, queryset)[source]

Return the filtered queryset.

class superdjango.db.audit.filters.ModifiedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for modified_by.

class superdjango.db.audit.filters.ViewedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for viewed_by.

utils

superdjango.db.audit.utils.is_audit_model(model_or_instance)[source]

Indicates whether the given model or model instance is auditable, e.g. it extends AuditMixin.

Parameters

model_or_instance – The model (class) or instance to be checked.

Return type

bool

Calculated Fields

planning library

Provides support for standard calculated fields as well as creating your own calculated fields.

Component Reference: Calculated Fields

fields

class superdjango.db.calculated.fields.CalculatedFieldMixin(**kwargs)[source]

Bases: object

Mixin for automatically calculate the value of the field from two or more other integer fields.

__init__(**kwargs)[source]

Initialize the field.

Parameters
  • calculate_from (list) – A list of field names upon which the calculation is based.

  • calculate_type (str | callable) – The type of calculation to perform; one of avg, max,``min`` or total. A callable may also be given. Defaults to total.

If a callable is provided for``calculate_type``, it must accept a dictionary of field name field value pairs to be calculated. It must also return a value of the appropriate type.

During init, the check_calculation_type() method is automatically called. You may need to override this if custom validation of the calculate_type is needed.

Note

Calculated fields are not editable.

Init will raise the following errors:

  • ImproperlyConfigured when no calculate_from is provided.

  • ValueError if the calculate_from is not given as a list or tuple.

  • ImproperlyConfigured when check_calculation_type() fails.

check_calculation_type()[source]

Check that the given calculation type is supported.

Return type

bool

get_calculated_value(model_instance, add)[source]

Get the calculated value. This method is called by the field’s pre_save() method.

pre_save(model_instance, add)[source]

Override to get calculated value

class superdjango.db.calculated.fields.CalculatedFloatField(**kwargs)[source]

Bases: superdjango.db.calculated.fields.CalculatedFieldMixin, django.db.models.fields.FloatField

Automatically calculate the value of the field from two or more other integer fields.

class superdjango.db.calculated.fields.CalculatedIntegerField(**kwargs)[source]

Bases: superdjango.db.calculated.fields.CalculatedFieldMixin, django.db.models.fields.IntegerField

Automatically calculate the value of the field from two or more other integer fields.

from superdjango.db.calculated.fields import CalculatedIntegerField

class Task(models.Model):
    pessimistic_estimate = models.IntegerField()
    optimistic_estimate = models.IntegerField()
    realistic_estimate = models.IntegerField()

    average_estimate = CalculatedIntegerField(
        _("average estimate"),
        calculate_from=[
            "pessimistic_estimate",
            "optimistic_estimate",
            "realistic_estimate",
        ],
        calculate_type=CalculatedIntegerField.AVERAGE
    )
class superdjango.db.calculated.fields.ConcatenatedCharField(**kwargs)[source]

Bases: superdjango.db.calculated.fields.CalculatedFieldMixin, django.db.models.fields.CharField

Concatenate char fields together.

__init__(**kwargs)[source]

Initialize a concatenated field.

Parameters

separator (str) – The separated used to concatenate the strings. Defaults to a space.

check_calculation_type()[source]

Always returns True.

get_calculated_value(model_instance, add)[source]

Get the concatenated string.

Completed Models

development library

Provides the ability to mark a record as complete.

Component Reference: Completed Models

admin

class superdjango.db.completed.admin.BaseCompletedByAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the CompletedByModel.

get_actions(request)[source]

Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

mark_complete(request, queryset)[source]

Mark a set of records as complete.

mark_incomplete(request, queryset)[source]

Mark a set of records as complete.

save_model(request, obj, form, change)[source]

Given a model instance save it to the database.

filters

Audit filters may be used in the Django Admin to create list filters using the full name of the user.

class superdjango.db.completed.filters.CompletedByListFilter(request, params, model, model_admin)[source]

Bases: django.contrib.admin.filters.SimpleListFilter

Filter for completed_by.

Order By

Ordering for the lookup defaults to USERNAME_FIELD. You can change this by setting SUPERDJANGO_ORDER_USERS_BY in your settings.py file.

Implementation

When extending, set the parameter_name to the name of the audit field.

lookups(request, model_admin)[source]

Must be overridden to return a list of tuples (value, verbose value)

queryset(request, queryset)[source]

Return the filtered queryset.

managers

class superdjango.db.completed.managers.CompletedManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Provide query filtering for completed records.

complete()[source]

Specifically select completed records.

incomplete()[source]

Specifically select incomplete records.

models

class superdjango.db.completed.models.CompletedByModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Tracks the user that marked a record as complete as well as the date and time the record was marked complete.

Completed may mean different things in different contexts. It just depends on your app.

Fields

This class will add the following fields:

  • cached_completed_by_name: Since the user is nullable, this captures the name of the user.

  • completed_by: The user that completed the record.

  • completed_dt: The date and time the record was completed.

  • is_complete: A boolean flag.

Methods

Conveniences methods have also been added for working with records.

  • mark_complete()

  • mark_incomplete()

  • toggle_complete()

Implementation

class Task(CompletedByModel):

    # ...

    class Meta:
        ordering = ["completed_dt"]
Parameters
  • cached_completed_by_name (CharField) – the name of the person that marked the record complete.

  • completed_by_id (ForeignKey) – Person that marked this complete.

  • completed_dt (DateTimeField) – Date and time of completion.

  • is_complete (BooleanField) – Indicates this is complete.

property completed_by_name

Alias for cached_completed_by_name.

mark_complete(user, commit=True)[source]

Mark the record as complete.

Parameters
  • user (AUTH_USER_MODEL) – The user marking the record as complete.

  • commit (bool) – Save the record after marking it as complete.

Note

Mark complete changes the record only if completed_dt is None. This prevents updating the user or date/time if mark_complete() is called more than once.

mark_incomplete(user, commit=True)[source]

Mark the record as incomplete.

Parameters
  • user (AUTH_USER_MODEL) – The user marking the record as complete.

  • commit (bool) – Save the record after marking it as incomplete.

toggle_complete(user, commit=True)[source]

Toggle the record’s completion, automatically setting it to whatever it currently is not.

Parameters
  • user (AUTH_USER_MODEL) – The user toggling the record.

  • commit (bool) – Save the record after marking it as incomplete.

Date/Time Models

development library

Fields and abstract models for working with dates and datetimes.

Component Reference: Date/Time Models

fields

class superdjango.db.datetime.fields.AutoNowAddDateTimeField(*args, **kwargs)[source]

Bases: django.db.models.fields.DateTimeField

Automatically sets the date/time to “now” when the record is created.

It uses Django’s timezone utils, which returns an aware or naive datetime, depending on settings.USE_TZ. However, use of USE_TZ is strongly recommended and is the default for new Django projects.

The editable field is also set to False by default.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

class superdjango.db.datetime.fields.AutoNowDateTimeField(*args, **kwargs)[source]

Bases: superdjango.db.datetime.fields.AutoNowAddDateTimeField

Extends AutoNowAddField to also add the current date/time whenever the record is saved.

pre_save(model_instance, add)[source]

Get the modified date/time automatically.

models

class superdjango.db.datetime.models.TimeStampedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

A base model for creating a record that includes added and modified datetime stamps.

Fields

  • added_dt: The date and time the record was created.

  • modified_dt: The date and time the record was last modified.

Parameters

Default Models

experimental library

Provides the ability to mark a record as the default of it’s type.

Component Reference: Default Models

admin

class superdjango.db.default.admin.BaseDefaultAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Add is_default to fields and list display/filter.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

managers

class superdjango.db.default.managers.DefaultManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Supports the DefaultModel.

from superdjango.db.default.managers import DefaultManager
from superdjango.db.default.models import DefaultModel

class Currency(DefaultModel):
    code = models.CharField(max_length=4)
    name = models.CharField(max_length=64)

default_currency = Currency.objects.default()
default()[source]

Get the default record.

mixins

class superdjango.db.default.mixins.DefaultMixin(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base class for implementing a “default” model.

This model supplies the methods for using the pre_save signal and to acquire the name of the field that provides the default flag.

static allow_one_default(sender, **kwargs)[source]

Use this when there can be only one is_default that is True.

classmethod get_default_flag_name()[source]

Get the name of the field that is used to mark the record as default.

Return type

str

classmethod get_default_rule(request=None)[source]

Get the rule to be applied; allow, ignore, require. Defaults to allow.

Parameters

request – If given, the rule may be determined dynamically.

Return type

str

static require_one_default(sender, **kwargs)[source]

Works like allow_one_default() but also ensures that the first record entered becomes the default.

models

class superdjango.db.default.models.DefaultModel(*args, **kwargs)[source]

Bases: superdjango.db.default.mixins.DefaultMixin

Allows a record to be marked as “default”.

This model is an implementation of :py:class`superdjango.db.default.mixins.DefaultMixin`, providing an is_default field.

Parameters

is_default (NullBooleanField) – Indicates that this is the default record.

Displayed Models

alpha library

Provides a consistent means of acquiring the human friendly name of a model instance.

Component Reference: Displayed Models

mixins

class superdjango.db.displayed.mixins.DisplayNameMixin[source]

Bases: object

Implement consistent proper naming for models that extend this class.

get_choice_name()[source]

Get the proper name of the record when used as a choice.

Return type

str

Tip

By default, this just returns get_display_name(), but may be overridden to provide a different name for choices than the regular display name.

get_display_name()[source]

Get the proper name for the current record.

Return type

str

Important

The extending class must impement this method.

models

class superdjango.db.displayed.models.DisplayNameModel(*args, **kwargs)[source]

Bases: superdjango.db.displayed.mixins.DisplayNameMixin, django.db.models.base.Model

Extend DisplayNameMixin to also cache the display name.

Parameters
  • cached_choice_name (CharField) – The proper name of the record when used as a choice.

  • cached_display_name (CharField) – The proper name of the record.

property choice_name

Get the cached name or the current name.

Return type

str

property display_name

Get the cached name or the current name.

Return type

str

save(*args, **kwargs)[source]

Cache the display name.

EAV Models

experimental library

Support for the Entity Attribute Value (EAV) approach to adding custom fields.

Component Reference: EAV Models

admin

class superdjango.db.eav.admin.BaseAttributeModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin for an attribute model.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

class superdjango.db.eav.admin.BaseAttributeModelInline(parent_model, admin_site)[source]

Bases: django.contrib.admin.options.StackedInline

Base inline for including attributes fields.

get_fields(request, obj=None)[source]

Hook for specifying fields.

class superdjango.db.eav.admin.BaseValueModelInline(parent_model, admin_site)[source]

Bases: django.contrib.admin.options.TabularInline

Base inline for specifying an attribute value.

get_fields(request, obj=None)[source]

Hook for specifying fields.

constants

class superdjango.db.eav.constants.DATA_TYPE[source]

Bases: object

The data type of a custom field.

mappings

superdjango.db.eav.mappings.CUSTOM_FIELD_MAPPINGS = {'boolean': <class 'django.forms.fields.BooleanField'>, 'date': <class 'django.forms.fields.DateField'>, 'datetime': <class 'django.forms.fields.DateTimeField'>, 'decimal': <class 'django.forms.fields.DecimalField'>, 'duration': <class 'django.forms.fields.DurationField'>, 'email': <class 'django.forms.fields.EmailField'>, 'float': <class 'django.forms.fields.FloatField'>, 'integer': <class 'django.forms.fields.IntegerField'>, 'ip': <class 'django.forms.fields.GenericIPAddressField'>, 'list': <class 'django.forms.fields.ChoiceField'>, 'slug': <class 'django.forms.fields.SlugField'>, 'text': <class 'django.forms.fields.CharField'>, 'time': <class 'django.forms.fields.TimeField'>, 'url': <class 'django.forms.fields.URLField'>, 'varchar': <class 'django.forms.fields.CharField'>}

Map EAV data types to form fields.

models

class superdjango.db.eav.models.AttributeModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base model for implementing extra attributes to be associated with a model.

Parameters
  • choices (TextField) – Used for the list data type. One choice per line.

  • content_type_id (ForeignKey) – Prompt the user to choose options from the selected content type.

  • decimal_places (PositiveSmallIntegerField) – Decimal places for decimal fields.

  • data_type (CharField) – Data type

  • grouping (CharField) – The fieldset or tab into which the field is organized.

  • help_text (TextField) – Help displayed to the user regarding the attribute.

  • is_enabled (BooleanField) – Indicates the attribute is available for use.

  • is_hidden (NullBooleanField) – Use this to hide options that are not configurable by the user. Be sure to specify a default.

  • is_required (BooleanField) – Make input for this attribute required. Be careful!

  • label (CharField) – A label or title of the attribute.

  • limit_choices_to (CharField) – A filter statement in JSON format that may be used to limit content type choices.

  • max_digits (PositiveSmallIntegerField) – Max number of digits for decimal fields.

  • max_length (PositiveSmallIntegerField) – Max number of characters for single-line text.

  • min_length (PositiveSmallIntegerField) – Minimum number of characters for single-line text.

  • name (CharField) – The name may be used as an identifier in reports, exports, and customizations.

  • raw_default_value (CharField) – The default value, if any. However, it is recommended that all attributes have a default.

  • sort_order (SmallIntegerField) – Sort order

clean()[source]

Make sure choices or content type has been provided for DATA_TYPE.LIST. Hidden values also require a default.

property default_value

Alias for get_default().

get_choices()[source]

Get the valid choices for the attribute.

Return type

list

get_default()[source]

Get the default value based on data_type.

Return type

int | float | str | None

property has_choices

Indicates whether choices have been defined for the value.

Return type

bool

save(*args, **kwargs)[source]

Automatically generate the name.

property value

Always returns the value of get_default(). Conforms to the API for ValueModel.

class superdjango.db.eav.models.ValueModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base class for specifying the value of an attribute.

You must define the attribute foreign key as well as a foreign key to the model to which this value is added.:

from superdjango.db.eav.models import AttributeModel, ValueModel

class Profile(models.Model):
    # ...

class ExtraAttribute(AttributeModel):
    # ...

class ExtraAttributeValue(ValueModel):

    attribute = models.ForeignKey(
        ExtraAttribute,
        related_name="values"
    )

    profile = models.ForeignKey(
        Profile,
        related_name="attributes"
    )

    def get_attribute(self):
        return self.attribute
Parameters

raw_value (TextField) – Value

property choices

Alias for get_choices().

property data_type

Alias for the attribute’s data_type.

property decimal_places

Alias for the attribute’s decimal_places.

display_value()[source]

Display the human-friendly value the attribute.

Return type

float | int | str

get_attribute()[source]

Get the attribute instance.

Return type

BaseType[AttributeModel]

get_choices()[source]

Alias for the attribute’s get_choices().

get_content_object()[source]

Get the content object associated with the value when a content type is used.

get_value()[source]

Get the actual value of the attribute based on the data_type.

property help_text

Alias for the attribute’s help_text.

property is_required

Alias for the attribute’s is_required.

property label

Alias for the attribute’s label.

property max_digits

Alias for the attribute’s max_digits.

property max_length

Alias for the attribute’s max_length.

property min_length

Alias for the attribute’s min_length.

property name

Alias for the attribute’s name.

property sort_order

Alias for the attribute’s sort_order.

property value

Alias for get_value().

ui

class superdjango.db.eav.ui.BaseAttributeInlineModelUI(parent_model, current_site=None)[source]

Bases: superdjango.ui.options.interfaces.InlineModelUI

Base inline for including attributes fields.

class superdjango.db.eav.ui.BaseAttributeModelUI(site=None)[source]

Bases: superdjango.ui.options.interfaces.ModelUI

Base UI for an attribute model.

Expiration Models

planning library

Work with records that have an expiration date and time.

Component Reference: Expiration Models

managers

class superdjango.db.expiration.managers.ExpirationManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Works in conjunction with ExpirationModel to filter by expiration.

expired()[source]

Get records that have expired.

Return type

QuerySet

expiry()[source]

Update all expired records.

Warning

This updates the database.

get_queryset()[source]

Provide custom queryset.

unexpired()[source]

Get records that have not yet expired.

class superdjango.db.expiration.managers.ExpirationQuerySet(model=None, query=None, using=None, hints=None)[source]

Bases: django.db.models.query.QuerySet

Works in conjunction with ExpirationModel to help filter out records that have expired.

expired()[source]

Filter for records that have expired.

unexpired()[source]

Filter for records that have not expired.

class superdjango.db.expiration.managers.ExpiredManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Work only with expired records.

get_queryset()[source]

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class superdjango.db.expiration.managers.UnExpiredManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Work only with unexpired records.

get_queryset()[source]

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

models

class superdjango.db.expiration.models.ExpirationModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Allows a model to (semi) automatically expire.

Note

There are several options for managers. It is left to the developer to decide which ones are needed.

Parameters
  • expiration_dt (DateTimeField) – Date and time the record should expire.

  • has_expired (BooleanField) – Indicates the record has expired.

is_past_expiration()[source]

Determine whether the record has expired.

Return type

bool

Returns

True if the record is past the expiration date.

History Models

planning library

Abstract model for implementing audit history on models.

Component Reference: History Models

admin

class superdjango.db.history.admin.BaseHistoryModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base class for history admin.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

get_readonly_fields(request, obj=None)[source]

Hook for specifying custom readonly fields.

has_add_permission(request)[source]

Return True if the given request has permission to add an object. Can be overridden by the user in subclasses.

has_delete_permission(request, obj=None)[source]

Return True if the given request has permission to change the given Django model instance, the default implementation doesn’t examine the obj parameter.

Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the obj model instance. If obj is None, this should return True if the given request has permission to delete any object of the given type.

constants

superdjango.db.history.constants.CREATE_VERBS = ('add', 'added', 'create', 'created', 'new')

A list of recognized record creation verbs.

superdjango.db.history.constants.DELETE_VERBS = ('delete', 'deleted', 'remove', 'removed')

A list of recognized record deletion verbs.

superdjango.db.history.constants.DETAIL_VERBS = ('detail', 'view', 'viewed')

A list of recognized record detail verbs.

superdjango.db.history.constants.UPDATE_VERBS = ('change', 'changed', 'edit', 'edited', 'update', 'updated')

A list of recognized record update verbs.

models

class superdjango.db.history.models.HistoryModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

An abstract model for implementing a running record history.

from superdjango.db.history.models import HistoryModel

class LogEntry(HistoryModel):

    class Meta:
        get_latest_by = "added_dt"
        ordering = ["-added_dt"]
        verbose_name = _("Log Entry")
        verbose_name_plural = _("Log Entries")
Parameters
  • absolute_url (CharField) – The URL of the model instance.

  • added_dt (DateTimeField) – Date and time the action was taken.

  • content_type_id (ForeignKey) – The internal content type of the object.

  • object_id (CharField) – The object (record) ID.

  • object_label (CharField) – The string representation of the object, i.e. it’s title, label, etc.

  • user_id (ForeignKey) – The user that performed the action.

  • user_name (CharField) – The name of the user that performed the action.

  • verb (CharField) – The verb (action) taken on a record.

  • verb_display (CharField) – The display value of the verb.

  • verbose_name (CharField) – The verbose name of the model.

property action

An alias for get_verb_display().

classmethod get_for(record, limit=10)[source]

Get history entries for a given record.

Parameters
  • record – The record (model instance) for which history is to be acquired.

  • limit (int) – The max number of history records to return.

Return type

django.db.models.QuerySet

get_message()[source]

Get the message that describes the action.

Return type

str

Note

The added date/time of the entry is not localized for the current user’s timezone. To support this, you’ll need to implement the message in a template.

get_object()[source]

Get the model instance that was the subject of the entry.

Returns

The model instance. If the object was deleted, None is returned.

get_url()[source]

Get the URL of the model instance.

The URL may not be available. Additionally, if the action represents a delete, no URL is returned.

Return type

str | None

get_verb_display()[source]

Get the human-friendly verb.

Return type

str

property is_create

Indicates the action is an addition.

Return type

bool

property is_delete

Indicates the action is a delete.

Return type

bool

property is_detail

Indicates the action is a detail.

Return type

bool

property is_update

Indicates the action was an update.

Return type

bool

classmethod log(record, user, verb, fields=None, url=None, verb_display=None)[source]

Create a new history entry.

Parameters
  • record – The model instance.

  • user – The user (instance) performing the action.

  • verb (str) – The action taken.

  • fields (list[superdjango.db.history.utils.FieldChange]) – A list of changed fields.

  • url (str) – The URL of the model instance. Typically that of the detail view. If omitted, an attempt will be made to acquire the URL from get_absolute_url().

  • verb_display (str) – The human0friendly name of the action taken.

Returns

The log entry instance.

Note

By default, nothing is done with fields. When you extend the class, you may save the fields to the extending model, or iterate over them to save each change to a separate model that refers back to the new history instance. See log_field_changes().

classmethod log_field_changes(instance, verb, fields=None)[source]

Log changes to fields.

Parameters
  • instance – The history record, NOT the original model instance.

  • verb (str) – The action taken. This allows verbs such as create or delete to be ignored.

  • fields (list[superdjango.db.history.utils.FieldChange]) – A list of changed fields.

property message

An alias for get_message().

property performed_by

Get the name of the user that performed the action.

Return type

str

ui

class superdjango.db.history.ui.BaseHistoryModelUI(site=None)[source]

Bases: superdjango.ui.options.interfaces.ModelUI

Base class for UI based on HistoryModel.

check_permission(request, verb, field=None, record=None)[source]

Only super users have delete access. All others are checked only for detail and list permissions.

utils

class superdjango.db.history.utils.FieldChange(field_name, new_value, old_value, label=None)[source]

Bases: object

Wraps the change that has occurred to a given field.

__init__(field_name, new_value, old_value, label=None)[source]

Initialize a field change.

Parameters
  • field_name (str) – The name of the field that was changed.

  • new_value – The new value, e.g. from the cleaned data of a form.

  • old_value – The existing value from the database prior to save.

  • label (str) – The field label (verbose name).

superdjango.db.history.utils.get_field_changes(form, model, record=None)[source]

Get the changed fields for a given form and record.

Parameters
  • form – The validated form instance.

  • model – The model class represented by the record.

  • record – The current record instance. It is safe to pass None.

Return type

list[superdjango.db.history.utils.FieldChange]

Returns

A list pf changed fields when record is not None. Otherwise, an empty list.

Locked Models

planning library

Work with records that have been locked from update or delete.

Component Reference: Locked Models

admin

class superdjango.db.locked.admin.BaseLockedModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Add support for superdjango.db.locked.models.LockedModel.

Inspired by this SO question on disabling the delete link in the admin.

get_fields(request, obj=None)[source]

Add lock fields to the form. Override this to add your own fields or to remove these fields from the form.

get_list_display(request)[source]

Add lock fields to the display. Override this to add your own fields or to remove these fields from the list.

has_change_permission(request, obj=None)[source]

A record that is locked will suspend update permission.

Note

Super users always have the ability to change (and therefore lock/unlock) a record.

has_delete_permission(request, obj=None)[source]

A record that is locked will suspend delete permission.

save_model(request, obj, form, change)[source]

Override to act on is_locked field.

  • If True, lock_record() is called.

  • If False, unlock_record() is called.

  • If None, no action is taken.

managers

class superdjango.db.locked.managers.LockedManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Works in conjunction with LockedModel to identify locked records.

Note

If you want to always work with locked records, LockedManager must be the default manager.

locked()[source]

Get only locked records.

unlocked()[source]

Get only unlocked records.

models

class superdjango.db.locked.models.LockedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

A model that prevents itself from being deleted or updated.

Parameters
  • is_locked (NullBooleanField) – Indicates this record should not be deleted.

  • locked_by_id (ForeignKey) – The user that locked the record.

  • locked_dt (DateTimeField) – Date and time the record was locked.

lock_record(user, commit=True)[source]

Lock the record.

Parameters
  • user (AUTH_USER_MODEL) – The user instance.

  • commit (bool) – Save after locking.

Note

Nothing is done if the record is already locked.

unlock_record(user, commit=True)[source]

Unlock the record.

Parameters
  • user (AUTH_USER_MODEL) – The user instance.

  • commit (bool) – Save after unlocking.

Note

Nothing is done if the record is already unlocked.

Lookup Models

development library

Provides pre-defined models for managing lookup (aka validation) data.

Component Reference: Lookup Models

admin

class superdjango.db.lookups.admin.BaseLookupAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base class for creating Django admin models for lookups.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

get_prepopulated_fields(request, obj=None)[source]

Hook for specifying custom prepopulated fields.

get_search_fields(request)[source]

Return a sequence containing the fields to be searched whenever somebody submits a search query.

models

class superdjango.db.lookups.models.IntegerLookupModel(*args, **kwargs)[source]

Bases: superdjango.db.lookups.models.LookupModel

Create a lookup with an integer value.

Parameters
  • abbr (CharField) – Enter the common abbreviation for the entry, if any.

  • description (TextField) – Brief description of the entry.

  • is_enabled (BooleanField) – Indicates the lookup is enabled for use.

  • label (CharField) – Official name or title for the entry.

  • value (IntegerField) – The value of the lookup.

class superdjango.db.lookups.models.LookupModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base class for lookup models.

Parameters
  • abbr (CharField) – Enter the common abbreviation for the entry, if any.

  • description (TextField) – Brief description of the entry.

  • is_enabled (BooleanField) – Indicates the lookup is enabled for use.

  • label (CharField) – Official name or title for the entry.

get_choice_name()[source]

Comply with the API for supdjango.db.display.models.DisplayNameMixin.

get_display_name()[source]

Comply with the API for supdjango.db.display.models.DisplayNameMixin.

class superdjango.db.lookups.models.StringLookupModel(*args, **kwargs)[source]

Bases: superdjango.db.lookups.models.LookupModel

Create a lookup with a string value.

Parameters
  • abbr (CharField) – Enter the common abbreviation for the entry, if any.

  • description (TextField) – Brief description of the entry.

  • is_enabled (BooleanField) – Indicates the lookup is enabled for use.

  • label (CharField) – Official name or title for the entry.

  • value (CharField) – The value of the lookup.

Owned Models

development library

Provides a random character field.

Component Reference: Owned Models

admin

class superdjango.db.owned.admin.BaseOwnedByAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the OwnedByModel.

get_actions(request)[source]

Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

set_current_owner(request, queryset)[source]

Set record ownership to the current user.

filters

Audit filters may be used in the Django Admin to create list filters using the full name of the user.

class superdjango.db.owned.filters.OwnedByListFilter(request, params, model, model_admin)[source]

Bases: django.contrib.admin.filters.SimpleListFilter

Filter for owned_by.

Order By

Ordering for the lookup defaults to first_name. You can change this by setting SUPERDJANGO_ORDER_USERS_BY in your settings.py file.

Implementation

When extending, set the parameter_name to the name of the audit field.

lookups(request, model_admin)[source]

Must be overridden to return a list of tuples (value, verbose value)

queryset(request, queryset)[source]

Return the filtered queryset.

managers

class superdjango.db.owned.managers.OwnedByManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Manage records that are “owned” by a user.

class Task(OwnedByModel):
    objects = OwnedByManager()

my_tasks = Task.objects.owned_by(user)
owned_by(user)[source]

Get records owned by the given users.

Parameters

user (AUTH_USER_MODEL) – The user that owns the records.

models

class superdjango.db.owned.models.OwnedByModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Identifies a user that owners the record, as distinct from the user that creates or modifies the record.

Fields

This class will add the following fields:

  • owned_by The user that owns the record.

Implementation

class Business(OwnedByModel):
    # ...
Parameters

owned_by_id (ForeignKey) – Select the user that owns the record.

set_record_owner(user, commit=True)[source]

Set the owner of the record.

Parameters
  • user (AUTH_USER_MODEL) – The user that owns the record.

  • commit (bool) – Save the record.

Parent-Tree Models

experimental library

Provides a simple model for implementing parent-child-sibling relationships.

Component Reference: Parent-Tree Models

models

class superdjango.db.parent.models.ParentTreeModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

A simple implementation of tree-like functionality using only a parent field that refers to self.

Note that some methods will be horribly inefficient, yet effective at finding all of the records associated with the current instance. If performance is a concern, then you may wish to review the following resources:

Parameters
  • cached_level (PositiveSmallIntegerField) – Level

  • parent_id (ForeignKey) – Parent

get_ancestors()[source]

Get the parent, grandparent, etc. for the current record.

Return type

list

Note

The list is populated from nearest ancestor to furthest ancestor. Use reversed() as needed to re-order the list so that the top-most ancestor is first.

get_children()[source]

Get the child records that are directly connected to the current record.

Return type

django.db.models.QuerySet

get_descendants()[source]

Get all of the descendants (children, grandchildren, etc.) for this record.

Return type

list

get_level(cached=True)[source]

Get the level of the record within the hierarchy.

Parameters

cached (bool) – Indicates whether cache should be used.

Return type

int

get_siblings()[source]

Get the records that are directly connected to the record’s parent.

Return type

django.db.models.QuerySet | None

has_children()[source]

Indicates whether the record has child records associated with it.

Return type

bool

has_parent()[source]

Indicates whether this record has a parent record.

Return type

bool

has_siblings()[source]

Indicates whether this record’s parent has other child records.

Return type

bool

property level

An alias of get_level().

save(*args, **kwargs)[source]

Automatically save cached_level.

utils

class superdjango.db.parent.utils.Diagram(record)[source]

Bases: object

Utility for graphing a parent-tree model instance.

__init__(record)[source]

Initialize the graph.

Parameters

record – The model instance.

static get_color(instance)[source]

Get the color to use for a record.

Parameters

instance – The model instance.

Return type

str

static get_display_name(instance)[source]

Get the human-friendly name of a record.

Parameters

instance – The model instance.

Return type

str

static get_node_options(node)[source]

Get the options for graphing the given node. See to_graph().

Parameters

node (Node) – The node for which options are to be provided.

Return type

str

get_structure()[source]

Get the structure of the record and its children.

Return type

Node

to_graph()[source]

Get the record as a graph ready for rendering.

Return type

RenderTreeGraph

See also: get_structure().

superdjango.db.parent.utils.get_ancestors(record, ancestors=None)[source]

Get the ancestors of a given model instance.

Parameters
  • record – The model instance.

  • ancestors (list) – The existing list of ancestors. Used when overloading.

Return type

list

superdjango.db.parent.utils.get_descendants(parent, descendants=None)[source]

Get the descendants of a given model instance.

Parameters
  • parent – The model instance.

  • descendants (list) – The existing list of ancestors. Used when overloading.

Return type

list

Polymorphic Models

experimental library

Managers and mixins for polymorphic behavior.

Component Reference: Polymorphic Models

managers

This code was copied and adapted from django-model-utils, and originally contributed to that package by Jeff Elmore.

The original license is preserved below:

Copyright (c) 2009-2019, Carl Meyer and contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.
    * Neither the name of the author nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class superdjango.db.polymorphic.managers.PolymorphicManager(*args, **kwargs)[source]

Bases: superdjango.db.polymorphic.managers.PolymorphicManagerMixin, django.db.models.manager.Manager

A polymorphic manager.

models

class superdjango.db.polymorphic.models.PolymorphicMixin(*args, **kwargs)[source]

Bases: django.db.models.base.Model

A mixin for models that extend a polymorphic model.

The purpose of which is to provide a means of acquiring the pointer field that refers back to the parent model.

classmethod get_pointer_field()[source]

Get the field instance for the pointer field.

Raise

DeeplyDisturbingError

Warning

The first non-abstract parent is used for identifying the pointer field. If you encounter issues with this, override the method and return the correct field.

static is_polymorphic_model()[source]

Indicates the model implements polymorphic behavior.

Return type

bool

utils

superdjango.db.polymorphic.utils.dump_polymorphic_data(model_name)[source]

Dump JSON data for the given model.

Parameters

model_name (str) – The model to export in app_name.ModelName format.

Return type

str

Raise

DeeplyDisturbingError

Primary Models

experimental library

Provides support for a publishing workflow.

Component Reference: Primary Models

admin

class superdjango.db.primary.admin.BasePrimaryAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Add is_primary to fields and list display/filter.

get_fields(request, obj=None)[source]

Hook for specifying fields.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

managers

class superdjango.db.primary.managers.PrimaryManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Supports the PrimaryModel.

from superdjango.db.primary.managers import PrimaryManager
from superdjango.db.primary.models import PrimaryModel

class EmergencyContact(PrimaryModel):
    employee = models.ForeignKey(Employee, related_name="emergency_contacts")
    # ...

employee = Employee.objects.get(pk=1)
contact = employee.emergency_contacts.primary()
primary()[source]

Get the primary record.

mixins

class superdjango.db.primary.mixins.PrimaryMixin(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Base class for implementing a “primary” model.

This model supplies the methods for using the pre_save signal and to acquire the name of the field that provides the primary flag.

static allow_one_primary(sender, **kwargs)[source]

Use this when there can be only one is_primary that is True. See allow_one_default for implementation example.

classmethod get_primary_flag_name()[source]

Get the name of the field that is used to mark the record as primary.

Return type

str

static require_one_primary(sender, **kwargs)[source]

Works like allow_one_primary() but also insures that the first record entered becomes the primary.

models

class superdjango.db.primary.models.PrimaryModel(*args, **kwargs)[source]

Bases: superdjango.db.primary.mixins.PrimaryMixin

Allows a record to be marked as “primary”.

This model supplies the following:

  • A NullBooleanField called is_primary.

  • Two static methods for use with the pre_save signal: allow_one_primary() and require_one_primary().

# models.py
from django.db import models
from superdjango.db.primary.models import PrimaryModel

class Address(models.Model):
    # A contact's address.

class Contact(models.Model):
    # A contact in an address book.

class LinkContactAddress(PrimaryModel):
    # Connect contacts with addresses.

    address = models.ForeignKey(Address)
    contact = models.ForeignKey(Contact)

# receivers.py
from django.db.models.signals import pre_save
from .models import LinkContactAddress

pre_save.connect(
    LinkContactAddress.allow_one_primary,
    LinkContactAddress,
    dispath_uid="linkcontactaddress_allow_one_primary"
)

# Or to require a primary record.
pre_save.connect(
    LinkContactAddress.require_one_primary,
    LinkContactAddress,
    dispath_uid="linkcontactaddress_require_one_primary"
)
Parameters

is_primary (NullBooleanField) – Indicates that this is the primary record.

Published Models

development library

Provides support for a publishing workflow.

Component Reference: Published Models

admin

class superdjango.db.published.admin.BasePublishedByModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the PublishedByModel.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

filters

class superdjango.db.published.filters.PublishedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for published_by.

models

class superdjango.db.published.models.PublishedByModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Represents a record (content of some sort) that may be published or unpublished.

Fields

The following fields are provided:

  • is_published

  • published_dt

  • published_by

Parameters
  • is_published (BooleanField) – Indicates the content is published.

  • published_by_id (ForeignKey) – The user publishing the content.

  • published_dt (DateTimeField) – Date and time the news item was published.

mark_published(user, audit=True, commit=True)[source]

Publish the content.

Parameters
  • user (AUTH_USER_MODEL) – The user publishing the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

mark_unpublished(user, audit=True, commit=True)[source]

Un-publish the content.

Parameters
  • user (AUTH_USER_MODEL) – The user publishing the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

property published_by_name

Get the full name or user name of the user that published the record.

Return type

str

Random Models

experimental library

Provides a random character field.

Component Reference: Random Models

fields

class superdjango.db.random.fields.RandomCharField(*args, **kwargs)[source]

Bases: django.db.models.fields.CharField

Generates random characters when the field is saved.

Possible Uses

  • Create a confirmation token for password resets or account creation.

  • Assist with SPAM prevention.

__init__(*args, **kwargs)[source]

Initialize self. See help(type(self)) for accurate signature.

formfield(**kwargs)[source]

Return a django.forms.Field instance for this field.

generate_text()[source]

Generate the random text.

pre_save(model_instance, add)[source]

Set the value of the field to a random string of text.

Resolved Models

development library

Provides support for a resolution workflow.

Component Reference: Resolved Models

admin

class superdjango.db.resolved.admin.BaseResolvedByModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the ResolvedByModel.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

filters

class superdjango.db.resolved.filters.ResolvedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for resolved_by.

models

class superdjango.db.resolved.models.ResolvedByModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Represents a record (content of some sort) that may be resolved or unresolved.

Parameters
  • is_resolved (BooleanField) – Indicates the content is resolved.

  • resolved_by_id (ForeignKey) – The user resolving the content.

  • resolved_dt (DateTimeField) – Date and time the news item was resolved.

mark_resolved(user, audit=True, commit=True)[source]

Resolve the content.

Parameters
  • user (AUTH_USER_MODEL) – The user resolving the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

mark_unresolved(user, audit=True, commit=True)[source]

Un-publish the content.

Parameters
  • user (AUTH_USER_MODEL) – The user resolving the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

property resolved_by_name

Get the full name or user name of the user that resolved the record.

Return type

str

Reviewed Models

development library

Provides support for a review workflow.

Component Reference: Reviewed Models

admin

class superdjango.db.reviewed.admin.BaseReviewedByModelAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Base admin class for models implementing the ReviewedByModel.

get_list_display(request)[source]

Return a sequence containing the fields to be displayed on the changelist.

get_list_filter(request)[source]

Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page.

filters

class superdjango.db.reviewed.filters.ReviewedByListFilter(request, params, model, model_admin)[source]

Bases: superdjango.db.audit.filters.BaseAuditListFilter

Filter for reviewed_by.

models

class superdjango.db.reviewed.models.ReviewedByModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Represents a record (content of some sort) that may be reviewed.

Fields

The following fields are provided:

  • is_reviewed

  • reviewed_dt

  • reviewed_by

Parameters
  • is_reviewed (BooleanField) – Indicates the content is reviewed.

  • reviewed_by_id (ForeignKey) – The user reviewing the content.

  • reviewed_dt (DateTimeField) – Date and time the news item was reviewed.

mark_reviewed(user, audit=True, commit=True)[source]

Review the content.

Parameters
  • user (AUTH_USER_MODEL) – The user reviewing the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

mark_unreviewed(user, audit=True, commit=True)[source]

Un-review the content.

Parameters
  • user (AUTH_USER_MODEL) – The user publishing the content.

  • audit (bool) – Call the audit() method if this is also an audit model.

  • commit (bool) – Indicates the record should be saved.

property reviewed_by_name

Get the full name or user name of the user that reviewed the record.

Return type

str

Revised Models

experimental library

A simple package that allows saving revisions of a record.

Component Reference: Revised Models

managers

class superdjango.db.revised.managers.RevisionManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Automatically filters for revised records.

get_queryset()[source]

Add filter to get only the latest records, e.g. those that are not a previous revision.

models

class superdjango.db.revised.models.RevisedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Supports records with revisions.

Parameters
  • is_previous_revision (BooleanField) – Indicates this is a previous revision.

  • previous_revision_id (ForeignKey) – The last or previous version of the record.

  • revision_by_id (ForeignKey) – The user that created the revision.

  • revision_dt (DateTimeField) – Date and time the revision was created.

  • revision_number (IntegerField) – The revision number for the record.

save_revision(user, commit=True)[source]

Save a revision of the model.

Parameters
  • user (AUTH_USER_MODEL) – The user creating the revision.

  • commit (bool) – Whether to save immediately.

Tip

The original instance is also not saved when commit is False.

Warning

Related records are not changed or duplicated during the revision.

Returns

The revised record (model instance).

Sorted Models

experimental library

A model and utilities for implementing record sortation.

Component Reference: Sorted Models

models

class superdjango.db.sorted.models.SortedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Allow a model to be easily sortable.

Fields

  • sort_order

Implementation

from superdjango.db.sorted.models import SortedModel

class Task(SortedModel):
    # ...
    class Meta:
        ordering = ["sort_order"]
Parameters

sort_order (IntegerField) – How the record should be sorted.

static pre_save_sort_order(sender, instance, **kwargs)[source]

Insure that the sort_order has a value.

from django.db.models.signals import pre_save
from .models import Task

pre_save.connect(
    Task.pre_save_sort_order,
    Task,
    dispatch_uid="task_pre_save_sort_order"
)
update_sort_order(sort_order, commit=True)[source]

Move the record to a different position, shifting the other records around it.

Parameters
  • sort_order (int) – The new position.

  • commit (bool) – Indicates whether to save the record after the move.

utils

Sortation utilities are separated from the SortedModel in order to keep the model clean and prevent possible collisions or conflicts with method names.

They may still be used in a declarative manner, for example:

from superdjango.db.sorted import utils as sortation
from .models import Task

task = Task.objects.get(pk=1234)

if sortation.has_previous_record(task):
    previous_task = sortation.get_previous_record(task)

if sortation.has_next_record(task):
    next_task = sortation.get_next_record(task)
superdjango.db.sorted.utils.get_next_record(instance, **criteria)[source]

Get the next record, if one exists.

Parameters
  • instance – The instance to be checked.

  • criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.

Return type

models.Model

Returns

Returns the next instance or None if a next instance could not be found.

superdjango.db.sorted.utils.get_previous_record(instance, **criteria)[source]

Get the previous record, if one exists.

Parameters
  • instance – The instance to be checked.

  • criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.

Return type

models.Model

Returns

Returns the previous instance or None if a previous instance could not be found.

superdjango.db.sorted.utils.has_next_record(instance, **criteria)[source]

Indicates whether a record exists with a higher sort order.

Parameters
  • instance – The instance to be checked.

  • criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.

Return type

bool

superdjango.db.sorted.utils.has_previous_record(instance, **criteria)[source]

Indicates whether a record exists with a lower sort order.

Parameters
  • instance – The instance to be checked.

  • criteria (dict) – Additional criteria to be given. This is useful when the record is embedded in a hierarchy.

Return type

bool

superdjango.db.sorted.utils.is_sortable(instance)[source]

Determine whether a given instance is sortable.

Parameters

instance (object) – The instance to be checked.

Return type

bool

Returns

Returns True if the instance inherits from SortedModel or a sort_order attribute is defined on the instance.

Slug Fields

experimental library

Provides support for a automatic slug field.

Component Reference: Slug Fields

fields

class superdjango.db.slug.fields.AutoSlugField(*args, **kwargs)[source]

Bases: django.db.models.fields.SlugField

Automatically generate a slug from another field.

Parameters
  • from_field (str) – The field from which the slug will be populated. This field must exist within the same model.

  • slug_using (callable) – The function to use for creating the slug. Defaults to Django’s implementation of slugify().

Example of use:

class Project(models.Model):
    title = models.CharField(max_length=128)
    slug = AutoSlugField(from_field="title", max_length=128)
__init__(*args, **kwargs)[source]

Check for the presence of from_field and slug_using.

get_slug(model_instance)[source]

Generate the slug.

Parameters

model_instance – The current record (model instance).

Return type

str

pre_save(model_instance, add)[source]

Generate the slug.

class superdjango.db.slug.fields.UniqueAutoSlugField(*args, **kwargs)[source]

Bases: superdjango.db.slug.fields.AutoSlugField

Like superdjango.db.slug.fields.AutoSlugField, but adds a unique constraint.

Warning

Note that this causes additional database queries which may impact performance.

__init__(*args, **kwargs)[source]

Check for the presence of from_field and slug_using.

get_slug(model_instance)[source]

Generate the slug.

Parameters

model_instance – The current record (model instance).

Return type

str

utils

superdjango.db.slug.utils.unique_slugify(record, value, callback=None, field='slug', queryset=None)[source]

Get a unique slug for a model instance.

Parameters
  • record – The model instance.

  • value (str) – The value to be slugged.

  • callback (callable) – The function that converts the value to a slug.

  • field (str) – The name of the slug field.

  • queryset (django.db.models.QuerySet) – The queryset to use for finding duplicates. This will default to all records of the given record’s model.

Return type

str

Timed Models

experimental library

Create records that incorporate start/stop timing functionality.

Component Reference: Timed Models

models

class superdjango.db.timed.models.TimedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Provides date/time fields for noting a starting time and ending time, as well as convenience methods for

calculating elapsed time.

from superdjango.db.timed.models import TimedModel

class Meeting(TimedModel):

    end_date = models.DateField()
    end_time = models.TimeField()
    is_all_day = models.BooleanField()
    start_date = models.DateField()
    start_time = models.TimeField()
Parameters
  • timer_elapsed_seconds (PositiveIntegerField) – Total seconds elapsed from start to end.

  • timer_is_running (BooleanField) – Indicates whether the timer is running.

  • timer_start_dt (DateTimeField) – Date and time the timer was started.

  • timer_stop_dt (DateTimeField) – Date and time the timer was stopped.

property elapsed_duration

Get the elapsed duration either as the current timer_elapsed_seconds or by calling get_elapsed_duration().

Return type

timedelta

get_elapsed_duration()[source]

Get the time that has elapsed as a duration.

Return type

timedelta

get_elapsed_duration_display()[source]

Get a human-friendly display for the duration.

Return type

str

get_timer_elapsed_seconds()[source]

Get the number of seconds that have passed since the timer started until now or until the item ended, if a stop datetime is available.

Return type

int

This method will:

  • Calculate the elapsed seconds from the start datetime until the current datetime.

  • Also include the elapsed seconds already calculated.

reset_timer(user, commit=True)[source]

Reset the current timer.

Parameters
  • user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the audit() method will be called. Pass None to suppress this behavior.

  • commit (bool) – Indicates whether the record should be saved after resetting the timer.

Return type

int

Returns

The value of elapsed seconds prior to the reset.

This method will:

  • Remove the stop datetime and set elapsed seconds to 0.

  • Change the start datetime to the current datetime.

  • Ensure that the timer is still running.

start_timer(user, commit=True)[source]

Start the timer.

Parameters
  • user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the audit() method will be called. Pass None to suppress this behavior.

  • commit (bool) – Indicates whether the record should be saved after starting the timer.

Return type

int

Returns

The current elapsed seconds if the timer is already running. Otherwise, 0.

This method will:

  • Set the start datetime to the current datetime.

  • Ensure that the time is running.

  • Leave the elapsed seconds unchanged.

stop_timer(user, commit=True)[source]

Stop the timer.

Parameters
  • user (AUTH_USER_MODEL | None) – The user updating the record. If the record is an audit model, the audit() method will be called. Pass None to suppress this behavior.

  • commit (bool) – Indicates whether the record should be saved after stopping the timer.

Return type

int

Returns

The elpased seconds.

This method will:

  • Set the stop datetime to the current datetime.

  • Update the elapsed seconds.

  • Ensure that the time is not running.

Trashed Models

experimental library

Provides a workflow for trashed, but not deleted, models.

Component Reference: Trashed Models

managers

class superdjango.db.trashed.managers.TrashedManager(*args, **kwargs)[source]

Bases: django.db.models.manager.Manager

Work with records implementing TrashModel.

Example:

class MyModel(TrashModel):
    objects = models.Manager()
    trashcan = TrashManager()

Note

If you want to always filter out trashed records, this manager must be the default.

Emptying the trash can.

empty(confirmed=False, criteria=None)[source]

Empty the trash can by permanently removing all records marked as trash.

Parameters
  • confirmed (bool) – Indicates the removal is confirmed. This is an extra precaution to prevent unintended deletion.

  • criteria (dict) – Additional criteria.

Example of using additional criteria:

# models.py
from superdjango.db.audit.models import AddedByModel
from superdjango.db.trash.managers import TrashManager
from superdjango.db.trash.models import TrashModel

class Task(AddedByModel, TrashModel):
    trashcan = TrashManager()
    # ...


# views.py
class EmptyTrash(FormView):

    def form_valid(self, form):
        criteria = {
            'added_by': self.request.user,
        }
        Task.trashcan.empty(confirmed=True, criteria)
        # ...
get_queryset()[source]

By default, only available records are returned.

trashed()[source]

Return only trashed records.

class superdjango.db.trashed.managers.TrashedQuerySet(model=None, query=None, using=None, hints=None)[source]

Bases: django.db.models.query.QuerySet

Provide filtering for records implementing TrashModel.

available()[source]

Return records that aren’t in the trash.

trashed()[source]

Return only trashed records.

models

class superdjango.db.trashed.models.TrashedModel(*args, **kwargs)[source]

Bases: django.db.models.base.Model

Allow a record to be marked as “trashed” without deleting it.

Parameters
  • is_trashed (NullBooleanField) – Indicates this record is in the trash.

  • trashed_by_id (ForeignKey) – User that put the record in the trash.

  • trashed_dt (DateTimeField) – Date and time the record was trashed.

restore_record(commit=True)[source]

Remove the record in the trash.

Parameters

commit (bool) – Whether to save after updating the fields.

trash_record(user, commit=True)[source]

Put the record in the trash.

Parameters
  • user (AUTH_USER_MODEL) – The user instance.

  • commit (bool) – Whether to save after updating the fields.