Skip to content

nautobot.apps.models

Data model classes and utilities for app implementation.

nautobot.apps.models.AutoSlugField

Bases: AutoSlugField

AutoSlugField

By default, sets editable=True, blank=True, max_length=100, overwrite_on_add=False, unique=True Required arguments: populate_from Specifies which field, list of fields, or model method the slug will be populated from.

populate_from can traverse a ForeignKey relationship
by using Django ORM syntax:
    populate_from = 'related_model__field'

Optional arguments:

separator Defines the used separator (default: '-')

overwrite If set to True, overwrites the slug on every save (default: False)

overwrite_on_add If set to True, overwrites the provided slug on initial creation (default: False)

slugify_function Defines the function which will be used to "slugify" a content (default: :py:func:~django.template.defaultfilters.slugify )

It is possible to provide custom "slugify" function with the slugify_function function in a model class.

slugify_function function in a model class takes priority over slugify_function given as an argument to :py:class:~AutoSlugField.

Example

.. code-block:: python # models.py

from django.db import models
from django_extensions.db.fields import AutoSlugField

class MyModel(models.Model):
    def slugify_function(self, content):
        return content.replace('_', '-').lower()

    title = models.CharField(max_length=42)
    slug = AutoSlugField(populate_from='title')

Taken from django_extensions AutoSlugField Documentation.

get_slug_fields(model_instance, lookup_value)

Workaround for https://github.com/django-extensions/django-extensions/issues/1713.

nautobot.apps.models.BaseManager

Bases: Manager

Base manager class corresponding to BaseModel and RestrictedQuerySet.

Adds built-in natural key support, loosely based on django-natural-keys.

get_by_natural_key(*args)

Return the object corresponding to the provided natural key.

Generic implementation that depends on the model being a BaseModel subclass or otherwise implementing our natural_key_field_lookups property API. Loosely based on implementation from django-natural-keys.

nautobot.apps.models.BaseModel

Bases: Model

Base model class that all models should inherit from.

This abstract base provides globally common fields and functionality.

Here we define the primary key to be a UUID field and set its default to automatically generate a random UUID value. Note however, this does not operate in the same way as a traditional auto incrementing field for which the value is issued by the database upon initial insert. In the case of the UUID field, Django creates the value upon object instantiation. This means the canonical pattern in Django of checking self.pk is None to tell if an object has been created in the actual database does not work because the object will always have the value populated prior to being saved to the database for the first time. An alternate pattern of checking not self.present_in_database can be used for the same purpose in most cases.

composite_key: str property

Automatic "slug" string derived from this model's natural key, suitable for use in URLs etc.

A less naïve implementation than django-natural-keys provides by default, based around URL percent-encoding.

natural_slug: str property

Automatic "slug" string derived from this model's natural key. This differs from composite key in that it must be human-readable and comply with a very limited character set, and is therefore lossy. This value is not guaranteed to be unique although a best effort is made by appending a fragment of the primary key to the natural slug value.

present_in_database property

True if the record exists in the database, False if it does not.

csv_natural_key_field_lookups() classmethod

Override this method for models with Python @property as part of their natural_key_field_names.

Since CSV export for natural_key_field_names relies on database fields, you can override this method to provide custom handling for models with property-based natural keys.

get_absolute_url(api=False)

Return the canonical URL for this object in either the UI or the REST API.

natural_key()

Smarter default implementation of natural key construction.

  1. Handles nullable foreign keys (https://github.com/wq/django-natural-keys/issues/18)
  2. Handles variadic natural-keys (e.g. Location model - [name, parent__name, parent__parent__name, ...].)

natural_key_args_to_kwargs(args) classmethod

Helper function to map a list of natural key field values to actual kwargs suitable for lookup and filtering.

Based on django-natural-keys NaturalKeyQuerySet.natural_key_kwargs() method.

natural_key_field_lookups()

List of lookups (possibly including nested lookups for related models) that make up this model's natural key.

BaseModel provides a "smart" implementation that tries to determine this automatically, but you can also explicitly set natural_key_field_names on a given model subclass if desired.

This property is based on a consolidation of django-natural-keys ForeignKeyModel.get_natural_key_info(), ForeignKeyModel.get_natural_key_def(), and ForeignKeyModel.get_natural_key_fields().

Unlike get_natural_key_def(), this doesn't auto-exclude all AutoField and BigAutoField fields, but instead explicitly discounts the id field (only) as a candidate.

validated_save(*args, **kwargs)

Perform model validation during instance save.

This is a convenience method that first calls self.full_clean() and then self.save() which in effect enforces model validation prior to saving the instance, without having to manually make these calls seperately. This is a slight departure from Django norms, but is intended to offer an optional, simplified interface for performing this common workflow. The intended use is for user defined Jobs run via the nautobot-server nbshell command.

nautobot.apps.models.ChangeLoggedModel

Bases: Model

An abstract model which adds fields to store the creation and last-updated times for an object. Both fields can be null to facilitate adding these fields to existing instances via a database migration.

get_changelog_url()

Return the changelog URL for this object.

to_objectchange(action, *, related_object=None, object_data_extra=None, object_data_exclude=None)

Return a new ObjectChange representing a change made to this object. This will typically be called automatically by ChangeLoggingMiddleware.

nautobot.apps.models.CollateAsChar

Bases: Func

Disregard localization by collating a field as a plain character string. Helpful for ensuring predictable ordering.

nautobot.apps.models.CompositeKeyQuerySetMixin

Mixin to extend a base queryset class with support for filtering by composite_key=... as a virtual parameter.

Example:

>>> Location.objects.last().composite_key
'Durham;AMER'

Note that Location.composite_key is a @property, not a database field, and so would not normally be usable in a QuerySet query, but because RestrictedQuerySet inherits from this mixin, the following "just works":

>>> Location.objects.get(composite_key="Durham;AMER")
<Location: Durham>

This is a shorthand for what would otherwise be a multi-step process:

>>> from nautobot.core.models.utils import deconstruct_composite_key
>>> deconstruct_composite_key("Durham;AMER")
['Durham', 'AMER']
>>> Location.natural_key_args_to_kwargs(['Durham', 'AMER'])
{'name': 'Durham', 'parent__name': 'AMER'}
>>> Location.objects.get(name="Durham", parent__name="AMER")
<Location: Durham>

This works for QuerySet filter() and exclude() as well:

>>> Location.objects.filter(composite_key='Durham;AMER')
<LocationQuerySet [<Location: Durham>]>
>>> Location.objects.exclude(composite_key='Durham;AMER')
<LocationQuerySet [<Location: AMER>]>

composite_key can also be used in combination with other query parameters:

>>> Location.objects.filter(composite_key='Durham;AMER', status__name='Planned')
<LocationQuerySet []>

It will raise a ValueError if the deconstructed composite key collides with another query parameter:

>>> Location.objects.filter(composite_key='Durham;AMER', name='Raleigh')
ValueError: Conflicting values for key "name": ('Durham', 'Raleigh')

See also BaseModel.composite_key and utils.construct_composite_key()/utils.deconstruct_composite_key().

exclude(*args, composite_key=None, **kwargs)

Explicitly handle exclude(composite_key="...") by decomposing the composite-key into natural key parameters.

Counterpart to BaseModel.composite_key property.

filter(*args, composite_key=None, **kwargs)

Explicitly handle filter(composite_key="...") by decomposing the composite-key into natural key parameters.

Counterpart to BaseModel.composite_key property.

split_composite_key_into_kwargs(composite_key=None, **kwargs)

Helper method abstracting a common need from filter() and exclude().

Subclasses may need to call this directly if they also have special processing of other filter/exclude params.

nautobot.apps.models.ConfigContextModel

Bases: Model, ConfigContextSchemaValidationMixin

A model which includes local configuration context data. This local data will override any inherited data from ConfigContexts.

get_config_context()

Return the rendered configuration context for a device or VM.

nautobot.apps.models.ConfigContextSchemaValidationMixin

Mixin that provides validation of config context data against a json schema.

nautobot.apps.models.ContentTypeRelatedQuerySet

Bases: RestrictedQuerySet

get_for_model(model)

Return all self.model instances assigned to the given model.

get_for_models(models_)

Return all self.model instances assigned to the given _models.

nautobot.apps.models.CustomFieldModel

Bases: Model

Abstract class for any model which may have custom fields associated with it.

cf property

Convenience wrapper for custom field data.

custom_field_data property

Legacy interface to raw custom field data

TODO(John): remove this entirely when the cf property is enhanced

get_computed_field(key, render=True)

Get a computed field for this model, lookup via key. Returns the template of this field if render is False, otherwise returns the rendered value.

get_computed_fields(label_as_key=False, advanced_ui=None)

Return a dictionary of all computed fields and their rendered values for this model. Keys are the key value of each field. If label_as_key is True, label values of each field are used as keys.

get_custom_field_groupings(advanced_ui=None)

Return a dictonary of custom fields grouped by the same grouping in the form { : [(cf1, ), (cf2, ), ...], ... : [(cf8, ), (cf9, ), ...], ... }

get_custom_field_groupings_advanced()

This method exists to help call get_custom_field_groupings() in templates where a function argument (advanced_ui) cannot be specified. Return a dictonary of custom fields grouped by the same grouping in the form { : [(cf1, ), (cf2, ), ...], ... : [(cf8, ), (cf9, ), ...], ... } which have advanced_ui set to True

get_custom_field_groupings_basic()

This method exists to help call get_custom_field_groupings() in templates where a function argument (advanced_ui) cannot be specified. Return a dictonary of custom fields grouped by the same grouping in the form { : [(cf1, ), (cf2, ), ...], ... : [(cf8, ), (cf9, ), ...], ... } which have advanced_ui set to False

get_custom_fields(advanced_ui=None)

Return a dictionary of custom fields for a single object in the form {: value}.

get_custom_fields_advanced()

This method exists to help call get_custom_fields() in templates where a function argument (advanced_ui) cannot be specified. Return a dictionary of custom fields for a single object in the form {: value} which have advanced_ui set to True

get_custom_fields_basic()

This method exists to help call get_custom_fields() in templates where a function argument (advanced_ui) cannot be specified. Return a dictionary of custom fields for a single object in the form {: value} which have advanced_ui set to False

has_computed_fields(advanced_ui=None)

Return a boolean indicating whether or not this content type has computed fields associated with it. This can also check whether the advanced_ui attribute is True or False for UI display purposes.

nautobot.apps.models.CustomValidator

This class is used to register plugin custom model validators which act on specified models. It contains the clean method which is overridden by plugin authors to execute custom validation logic. Plugin authors must raise ValidationError within this method to trigger validation error messages which are propagated to the user. A convenience method validation_error(<message>) may be used for this purpose.

The model attribute on the class defines the model to which this validator is registered. It should be set as a string in the form <app_label>.<model_name>.

clean()

Implement custom model validation in the standard Django clean method pattern. The model instance is accessed with the object key within self.context, e.g. self.context['object']. ValidationError must be raised to prevent saving model instance changes, and propagate messages to the user. For convenience, self.validation_error(<message>) may be called to raise a ValidationError.

validation_error(message)

Convenience method for raising django.core.exceptions.ValidationError which is required in order to trigger validation error messages which are propagated to the user.

nautobot.apps.models.DynamicGroupMixin

Adds properties to a model to facilitate reversing DynamicGroup membership:

  • dynamic_groups - A QuerySet of DynamicGroup objects this instance is a member of, performs the most database queries.
  • dynamic_groups_cached - A QuerySet of DynamicGroup objects this instance is a member of, uses cached member list if available. Ideal for most use cases.
  • dynamic_groups_list - A list of DynamicGroup objects this instance is a member of, performs one less database query than dynamic_groups.
  • dynamic_groups_list_cached - A list of DynamicGroup objects this instance is a member of, uses cached member list if available. Performs no database queries in optimal conditions.

All properties are cached on the instance after the first call. To clear the instance cache without re-instantiating the object, call delattr(instance, "_[the_property_name]"). EX: delattr(instance, "_dynamic_groups")

dynamic_groups property

Return a queryset of DynamicGroup objects this instance is a member of.

This will NOT use the cached member lists of the dynamic groups and will always query the database for each DynamicGroup.

Additionally, this performs a final database query to turn the internal list into a queryset.

dynamic_groups_cached property

Return a queryset of DynamicGroup objects this instance is a member of.

This will use the cached member lists of the dynamic groups if available.

In optimal conditions this will incur a single database query to convert internal list into a queryset which is reasonably performant.

This is the ideal property to use for most use cases.

dynamic_groups_list property

Return a list of DynamicGroup objects this instance is a member of.

This will NOT use the cached member lists of the dynamic groups and will always query the database for each DynamicGroup.

This saves a final query to turn the list into a queryset.

dynamic_groups_list_cached property

Return a list of DynamicGroup objects this instance is a member of.

This will use the cached member lists of the dynamic groups if available.

In optimal conditions this will incur no database queries.

get_dynamic_groups_url()

Return the dynamic groups URL for a given instance.

nautobot.apps.models.EmptyGroupByJSONBAgg

Bases: JSONBAgg

JSONBAgg is a builtin aggregation function which means it includes the use of a GROUP BY clause. When used as an annotation for collecting config context data objects, the GROUP BY is incorrect. This subclass overrides the Django ORM aggregation control to remove the GROUP BY.

nautobot.apps.models.EnhancedURLValidator

Bases: URLValidator

Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension and enforce allowed schemes specified in the configuration.

nautobot.apps.models.ExclusionValidator

Bases: BaseValidator

Ensure that a field's value is not equal to any of the specified values.

nautobot.apps.models.ForeignKeyLimitedByContentTypes

Bases: ForeignKeyWithAutoRelatedName

An abstract model field that automatically restricts ForeignKey options based on content_types.

For instance, if the model "Role" contains two records: role_1 and role_2, role_1's content_types are set to "dcim.location" and "dcim.device" while the role_2's content_types are set to "circuit.circuit" and "dcim.location."

Then, for the field role on the Device model, role_1 is the only Role that is available, while role_1 & role_2 are both available for the Location model.

The limit_choices_to for the field are automatically derived from
  • the content-type to which the field is attached (e.g. dcim.device)

formfield(**kwargs)

Return a prepped formfield for use in model forms.

get_limit_choices_to()

Limit this field to only objects which are assigned to this model's content-type.

Note that this is implemented via specifying content_types__app_label= and content_types__model= rather than via the more obvious content_types=ContentType.objects.get_for_model(self.model) because the latter approach would involve a database query, and in some cases (most notably FilterSet definition) this function is called before database migrations can be run.

nautobot.apps.models.ForeignKeyWithAutoRelatedName

Bases: ForeignKey

Extend base ForeignKey functionality to create a smarter default related_name.

For example, "ip_addresses" instead of "ipaddress_set", "ipaddresss", or "ipam_ipaddress_related".

Primarily useful for cases of abstract base classes that define ForeignKeys, such as nautobot.dcim.models.device_components.ComponentModel.

nautobot.apps.models.JSONArrayField

Bases: JSONField

An ArrayField implementation backed JSON storage. Replicates ArrayField's base field validation.

deconstruct()

Return enough information to recreate the field as a 4-tuple
  • The name of the field on the model, if contribute_to_class() has been run.
  • The import path of the field, including the class:e.g. django.db.models.IntegerField This should be the most portable version, so less specific may be better.
  • A list of positional arguments.
  • A dict of keyword arguments.

formfield(**kwargs)

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

get_prep_value(value)

Perform preliminary non-db specific value checks and conversions.

run_validators(value)

Runs all validators against value and raise ValidationError if necessary. Some validators can't be created at field initialization time.

to_python(value)

Convert value into JSON, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value.

validate(value, model_instance)

Validate value and raise ValidationError if necessary.

value_to_string(obj)

Return a string value of this field from the passed obj. This is used by the serialization framework.

nautobot.apps.models.JSONBAgg

Bases: Aggregate

Like django.contrib.postgres.aggregates.JSONBAgg, but different.

  1. Supports both Postgres (JSONB_AGG) and MySQL (JSON_ARRAYAGG)
  2. Does not support ordering as JSON_ARRAYAGG does not guarantee ordering.

nautobot.apps.models.NameColorContentTypesModel

Bases: BaseModel, ChangeLoggedModel, CustomFieldModel, RelationshipModel, NotesMixin, DynamicGroupMixin

This abstract base properties model contains fields and functionality that are shared amongst models that requires these fields: name, color, content_types and description.

nautobot.apps.models.NaturalOrderingField

Bases: CharField

A field which stores a naturalized representation of its target field, to be used for ordering its parent model.

:param target_field: Name of the field of the parent model to be naturalized :param naturalize_function: The function used to generate a naturalized value (optional)

pre_save(model_instance, add)

Generate a naturalized value from the target field

nautobot.apps.models.NotesMixin

Adds a notes property that returns a queryset of Notes membership.

notes property

Return a Notes queryset for this instance.

get_notes_url(api=False)

Return the notes URL for a given instance.

nautobot.apps.models.OrganizationalModel

Bases: BaseModel, ChangeLoggedModel, CustomFieldModel, RelationshipModel, DynamicGroupMixin, NotesMixin

Base abstract model for all organizational models.

Organizational models aid the primary models by building structured relationships and logical groups, or categorizations. Organizational models do not typically represent concrete networking resources or assets, but rather they enable user specific use cases and metadata about network resources. Examples include Device Role, Rack Group, Status, Manufacturer, and Platform.

nautobot.apps.models.PrimaryModel

Bases: BaseModel, ChangeLoggedModel, CustomFieldModel, RelationshipModel, DynamicGroupMixin, NotesMixin

Base abstract model for all primary models.

A primary model is one which is materialistically relevant to the network datamodel. Such models form the basis of major elements of the data model, like Device, IP Address, Location, VLAN, Virtual Machine, etc. Primary models usually represent tangible or logical resources on the network, or within the organization.

nautobot.apps.models.RelationshipModel

Bases: Model

Abstract class for any model which may have custom relationships associated with it.

get_relationships(include_hidden=False, advanced_ui=None)

Return a dictionary of RelationshipAssociation querysets for all custom relationships

Returns:

Type Description
dict

{ "source": { <Relationship instance #1>: <RelationshipAssociation queryset #1>, <Relationship instance #2>: <RelationshipAssociation queryset #2>, }, "destination": { <Relationship instance #3>: <RelationshipAssociation queryset #3>, <Relationship instance #4>: <RelationshipAssociation queryset #4>, }, "peer": { <Relationship instance #5>: <RelationshipAssociation queryset #5>, <Relationship instance #6>: <RelationshipAssociation queryset #6>, }, }

get_relationships_data(**kwargs)

Return a dictionary of relationships with the label and the value or the queryset for each.

Used for rendering relationships in the UI; see nautobot/core/templates/inc/relationships_table_rows.html

Returns:

Type Description
dict

{ "source": { <Relationship instance #1>: { # one-to-one relationship that self is the source of "label": "...", "peer_type": <ContentType>, "has_many": False, "value": <model instance>, # single destination for this relationship "url": "...", }, <Relationship instance #2>: { # one-to-many or many-to-many relationship that self is a source for "label": "...", "peer_type": <ContentType>, "has_many": True, "value": None, "queryset": <RelationshipAssociation queryset #2> # set of destinations for the relationship }, }, "destination": { (same format as "source" dict - relationships that self is the destination of) }, "peer": { (same format as "source" dict - symmetric relationships that self is involved in) }, }

get_relationships_data_advanced_fields()

Same docstring as get_relationships_data() above except this only returns relationships where advanced_ui==True for displaying in the 'Advanced' tab on the object's page

get_relationships_data_basic_fields()

Same docstring as get_relationships_data() above except this only returns relationships where advanced_ui==False for displaying in the main object detail tab on the object's page

Parameters:

Name Type Description Default
output_for str

either "ui" or "api" depending on usage

'ui'
initial_data dict

submitted form/serializer data to validate against

None
relationships_key_specified bool

if the "relationships" key was provided or not

False
instance Optional[BaseModel]

an optional model instance to validate against

None

Returns: (list[dict]): List of field error dicts if any are found

nautobot.apps.models.RestrictedQuerySet

Bases: CompositeKeyQuerySetMixin, QuerySet

check_perms(user, *, instance=None, pk=None, action='view')

Check whether the given user can perform the given action with regard to the given instance of this model.

Either instance or pk must be specified, but not both.

Parameters:

Name Type Description Default
user User

User instance

required
instance model

Instance of this queryset's model to check, if pk is not provided

None
pk uuid

Primary key of the desired instance to check for, if instance is not provided

None
action str

The action which must be permitted (e.g. "view" for "dcim.view_location"); default is 'view'

'view'

Returns:

Type Description
bool

Whether the action is permitted or not

distinct_values_list(*fields, flat=False, named=False)

Wrapper for QuerySet.values_list() that adds the distinct() query to return a list of unique values.

Note

Uses QuerySet.order_by() to disable ordering, preventing unexpected behavior when using values_list described in the Django distinct() documentation at https://docs.djangoproject.com/en/stable/ref/models/querysets/#distinct

Parameters:

Name Type Description Default
*fields str

Optional positional arguments which specify field names.

()
flat bool

Set to True to return a QuerySet of individual values instead of a QuerySet of tuples. Defaults to False.

False
named bool

Set to True to return a QuerySet of namedtuples. Defaults to False.

False

Returns:

Type Description
QuerySet

A QuerySet of tuples or, if flat is set to True, a queryset of individual values.

restrict(user, action='view')

Filter the QuerySet to return only objects on which the specified user has been granted the specified permission.

:param user: User instance :param action: The action which must be permitted (e.g. "view" for "dcim.view_location"); default is 'view'

nautobot.apps.models.StatusField

Bases: ForeignKeyLimitedByContentTypes

Model database field that automatically limits custom choices.

The limit_choices_to for the field are automatically derived from:

- the content-type to which the field is attached (e.g. `dcim.device`)

contribute_to_class(cls, *args, **kwargs)

Overload default so that we can assert that .get_FOO_display is attached to any model that is using a StatusField.

Using .contribute_to_class() is how field objects get added to the model at during the instance preparation. This is also where any custom model methods are hooked in. So in short this method asserts that any time a StatusField is added to a model, that model also gets a .get_status_display() and a .get_status_color() method without having to define it on the model yourself.

nautobot.apps.models.StatusModel

Bases: Model

Deprecated abstract base class for any model which may have statuses.

Just directly include a StatusField instead for any new models.

nautobot.apps.models.TagsField

Bases: TaggableManager

Override FormField method on taggit.managers.TaggableManager to match the Nautobot UI.

nautobot.apps.models.TagsManager

Bases: _TaggableManager, BaseManager

Manager class for model 'tags' fields.

nautobot.apps.models.TreeManager

Bases: TreeManager, from_queryset(TreeQuerySet)

Extend django-tree-queries' TreeManager to incorporate RestrictedQuerySet.

max_depth property

Cacheable version of TreeQuerySet.max_tree_depth().

Generally TreeManagers are persistent objects while TreeQuerySets are not, hence the difference in behavior.

nautobot.apps.models.TreeModel

Bases: TreeNode

Nautobot-specific base class for models that exist in a self-referential tree.

display property

By default, TreeModels display their full ancestry for clarity.

As this is an expensive thing to calculate, we cache it for a few seconds in the case of repeated lookups.

nautobot.apps.models.TreeQuerySet

Bases: TreeQuerySet, RestrictedQuerySet

Combine django-tree-queries' TreeQuerySet with our RestrictedQuerySet for permissions enforcement.

ancestors(of, *, include_self=False)

Custom ancestors method for optimization purposes.

Dynamically computes ancestors either through the tree or through the parent foreign key depending on whether tree fields are present on of.

max_tree_depth()

Get the maximum tree depth of any node in this queryset.

In most cases you should use TreeManager.max_depth instead as it's cached and this is not.

root - depth 0 \ branch - depth 1 \ leaf - depth 2

Note that a queryset with only root nodes will return zero, and an empty queryset will also return zero. This is probably a bug, we should really return -1 in the case of an empty queryset, but this is "working as implemented" and changing it would possibly be a breaking change at this point.

nautobot.apps.models.ValidRegexValidator

Bases: RegexValidator

Checks that the value is a valid regular expression.

Don't confuse this with RegexValidator, which uses a regex to validate a value.

nautobot.apps.models.VarbinaryIPField

Bases: BinaryField

IP network address

db_type(connection)

Returns the correct field type for a given database vendor.

from_db_value(value, expression, connection)

Converts DB (varbinary) to Python (str).

get_db_prep_value(value, connection, prepared=False)

Converts Python (str) to DB (varbinary).

to_python(value)

Converts value to Python (str).

value_to_string(obj)

IPField is serialized as str(IPAddress())

nautobot.apps.models.array_to_string(array)

Generate an efficient, human-friendly string from a set of integers. Intended for use with ArrayField. For example: [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"

nautobot.apps.models.construct_composite_key(values)

Convert the given list of natural key values to a single URL-path-usable string.

  • Non-URL-safe characters are percent-encoded.
  • Null (None) values are percent-encoded as a literal null character %00.

Reversible by deconstruct_composite_key().

nautobot.apps.models.construct_natural_slug(values, pk=None)

Convert the given list of natural key values to a single human-readable string.

If pk is provided, it will be appended to the end of the natural slug. If the PK is a UUID, only the first four characters will be appended.

A third-party lossy slugify() function is used to convert each natural key value to a slug, and then they are joined with an underscore.

  • Spaces or repeated dashes are converted to single dashes.
  • Accents and ligatures from Unicode characters are reduced to ASCII.
  • Remove remaining characters that are not alphanumerics, underscores, or hyphens.
  • Converted to lowercase.
  • Strips leading/trailing whitespace, dashes, and underscores.
  • Each natural key value in the list is separated by underscores.
  • Emojis will be converted to their registered name.

This value is not reversible, is lossy, and is not guaranteed to be unique.

Return a Subquery suitable for annotating a child object count.

Parameters:

Name Type Description Default
model Model

The related model to aggregate

required
field str

The field on the related model which points back to the OuterRef model

required
filter_dict dict

Optional dict of filter key/value pairs to limit the Subquery

None

nautobot.apps.models.deconstruct_composite_key(composite_key)

Convert the given composite-key string back to a list of distinct values.

  • Percent-encoded characters are converted back to their raw values
  • Single literal null characters %00 are converted back to a Python None.

Inverse operation of construct_composite_key().

nautobot.apps.models.extras_features(*features)

Decorator used to register extras provided features to a model

nautobot.apps.models.find_models_with_matching_fields(app_models, field_names, field_attributes=None)

Find all models that have fields with the specified names, and return them grouped by app.

Parameters:

Name Type Description Default
app_models list[BaseModel]

A list of model classes to search through.

required
field_names list[str]

A list of names of fields that must be present in order for the model to be considered

required
field_attributes dict

Optional dictionary of attributes to filter the fields by.

None
Return

(dict): A dictionary where the keys are app labels and the values are sets of model names.

nautobot.apps.models.get_all_concrete_models(base_class)

Get a list of all non-abstract models that inherit from the given base_class.

nautobot.apps.models.get_default_namespace()

Return the Global namespace.

nautobot.apps.models.get_default_namespace_pk()

Return the PK of the Global namespace for use in default value for foreign keys.

nautobot.apps.models.is_taggable(obj)

Return True if the instance can have Tags assigned to it; False otherwise.

nautobot.apps.models.naturalize(value, max_length, integer_places=8)

Take an alphanumeric string and prepend all integers to integer_places places to ensure the strings are ordered naturally. For example:

location9router21
location10router4
location10router19

becomes:

location00000009router00000021
location00000010router00000004
location00000010router00000019

:param value: The value to be naturalized :param max_length: The maximum length of the returned string. Characters beyond this length will be stripped. :param integer_places: The number of places to which each integer will be expanded. (Default: 8)

nautobot.apps.models.naturalize_interface(value, max_length)

Similar in nature to naturalize(), but takes into account a particular naming format adapted from the old InterfaceManager.

:param value: The value to be naturalized :param max_length: The maximum length of the returned string. Characters beyond this length will be stripped.

nautobot.apps.models.pretty_print_query(query)

Given a Q object, display it in a more human-readable format.

Parameters:

Name Type Description Default
query Q

Query to display.

required

Returns:

Type Description
str

Pretty-printed query logic

Example

print(pretty_print_query(Q)) ( location__name='Campus-01' OR location__name='Campus-02' OR ( location__name='Room-01' AND status__name='Active' ) OR ( location__name='Building-01' AND ( NOT (location__name='Building-01' AND status__name='Decommissioning') ) ) )

nautobot.apps.models.serialize_object(obj, extra=None, exclude=None)

Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like change logging, not the REST API.) Optionally include a dictionary to supplement the object data. A list of keys can be provided to exclude them from the returned dictionary. Private fields (prefaced with an underscore) are implicitly excluded.

nautobot.apps.models.serialize_object_v2(obj)

Return a JSON serialized representation of an object using obj's serializer.

nautobot.apps.models.slugify_dashes_to_underscores(content)

Custom slugify_function - use underscores instead of dashes; resulting slug can be used as a variable name, as well as a graphql safe string. Note: If content starts with a non graphql-safe character, e.g. a digit This method will prepend an "a" to content to make it graphql-safe e.g: 123 main st -> a123_main_st

nautobot.apps.models.slugify_dots_to_dashes(content)

Custom slugify_function - convert '.' to '-' instead of removing dots outright.