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.
Source code in nautobot/core/models/fields.py
get_slug_fields(model_instance, lookup_value)
¶
Workaround for https://github.com/django-extensions/django-extensions/issues/1713.
Source code in nautobot/core/models/fields.py
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
.
Source code in nautobot/core/models/managers.py
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
.
Source code in nautobot/core/models/managers.py
nautobot.apps.models.BaseModel
¶
Bases: models.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.
Source code in nautobot/core/models/__init__.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
|
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.
Source code in nautobot/core/models/__init__.py
get_absolute_url(api=False)
¶
Return the canonical URL for this object in either the UI or the REST API.
Source code in nautobot/core/models/__init__.py
natural_key()
¶
Smarter default implementation of natural key construction.
- Handles nullable foreign keys (https://github.com/wq/django-natural-keys/issues/18)
- Handles variadic natural-keys (e.g. Location model - [name, parent__name, parent__parent__name, ...].)
Source code in nautobot/core/models/__init__.py
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.
Source code in nautobot/core/models/__init__.py
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.
Source code in nautobot/core/models/__init__.py
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.
Source code in nautobot/core/models/__init__.py
nautobot.apps.models.ChangeLoggedModel
¶
Bases: models.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.
Source code in nautobot/extras/models/change_logging.py
get_changelog_url()
¶
Return the changelog URL for this object.
Source code in nautobot/extras/models/change_logging.py
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.
Source code in nautobot/extras/models/change_logging.py
nautobot.apps.models.CollateAsChar
¶
Bases: Func
Disregard localization by collating a field as a plain character string. Helpful for ensuring predictable ordering.
Source code in nautobot/core/models/query_functions.py
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")
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()
.
Source code in nautobot/core/models/querysets.py
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.
Source code in nautobot/core/models/querysets.py
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.
Source code in nautobot/core/models/querysets.py
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.
Source code in nautobot/core/models/querysets.py
nautobot.apps.models.ConfigContextModel
¶
Bases: models.Model
, ConfigContextSchemaValidationMixin
A model which includes local configuration context data. This local data will override any inherited data from ConfigContexts.
Source code in nautobot/extras/models/models.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
get_config_context()
¶
Return the rendered configuration context for a device or VM.
Source code in nautobot/extras/models/models.py
nautobot.apps.models.ConfigContextSchemaValidationMixin
¶
Mixin that provides validation of config context data against a json schema.
Source code in nautobot/extras/models/models.py
nautobot.apps.models.ContentTypeRelatedQuerySet
¶
Bases: RestrictedQuerySet
Source code in nautobot/core/models/name_color_content_types.py
get_for_model(model)
¶
Return all self.model
instances assigned to the given model.
Source code in nautobot/core/models/name_color_content_types.py
get_for_models(models_)
¶
Return all self.model
instances assigned to the given _models
.
Source code in nautobot/core/models/name_color_content_types.py
nautobot.apps.models.CustomFieldModel
¶
Bases: models.Model
Abstract class for any model which may have custom fields associated with it.
Source code in nautobot/extras/models/customfields.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
|
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.
Source code in nautobot/extras/models/customfields.py
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.
Source code in nautobot/extras/models/customfields.py
get_custom_field_groupings(advanced_ui=None)
¶
Return a dictonary of custom fields grouped by the same grouping in the form
{
Source code in nautobot/extras/models/customfields.py
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
{
Source code in nautobot/extras/models/customfields.py
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
{
Source code in nautobot/extras/models/customfields.py
get_custom_fields(advanced_ui=None)
¶
Return a dictionary of custom fields for a single object in the form {
Source code in nautobot/extras/models/customfields.py
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 {
Source code in nautobot/extras/models/customfields.py
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 {
Source code in nautobot/extras/models/customfields.py
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.
Source code in nautobot/extras/models/customfields.py
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>
.
Source code in nautobot/extras/plugins/__init__.py
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.
Source code in nautobot/extras/plugins/__init__.py
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.
Source code in nautobot/extras/plugins/__init__.py
nautobot.apps.models.DynamicGroupMixin
¶
Adds properties to a model to facilitate reversing DynamicGroup membership:
dynamic_groups
- A QuerySet ofDynamicGroup
objects this instance is a member of, performs the most database queries.dynamic_groups_cached
- A QuerySet ofDynamicGroup
objects this instance is a member of, uses cached member list if available. Ideal for most use cases.dynamic_groups_list
- A list ofDynamicGroup
objects this instance is a member of, performs one less database query thandynamic_groups
.dynamic_groups_list_cached
- A list ofDynamicGroup
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")
Source code in nautobot/extras/models/mixins.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
|
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.
Source code in nautobot/extras/models/mixins.py
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.
Source code in nautobot/core/models/query_functions.py
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.
Source code in nautobot/core/models/validators.py
nautobot.apps.models.ExclusionValidator
¶
Bases: BaseValidator
Ensure that a field's value is not equal to any of the specified values.
Source code in nautobot/core/models/validators.py
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
)
Source code in nautobot/core/models/fields.py
formfield(**kwargs)
¶
Return a prepped formfield for use in model forms.
Source code in nautobot/core/models/fields.py
nautobot.apps.models.ForeignKeyWithAutoRelatedName
¶
Bases: models.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
.
Source code in nautobot/core/models/fields.py
nautobot.apps.models.JSONArrayField
¶
Bases: models.JSONField
An ArrayField implementation backed JSON storage. Replicates ArrayField's base field validation.
Source code in nautobot/core/models/fields.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
|
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.
Source code in nautobot/core/models/fields.py
formfield(**kwargs)
¶
Return a django.forms.Field instance for this field.
get_prep_value(value)
¶
Perform preliminary non-db specific value checks and conversions.
Source code in nautobot/core/models/fields.py
run_validators(value)
¶
Runs all validators against value
and raise ValidationError if necessary.
Some validators can't be created at field initialization time.
Source code in nautobot/core/models/fields.py
to_python(value)
¶
Convert value
into JSON, raising django.core.exceptions.ValidationError
if the data can't be converted. Return the converted value.
Source code in nautobot/core/models/fields.py
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.
Source code in nautobot/core/models/fields.py
nautobot.apps.models.JSONBAgg
¶
Bases: Aggregate
Like django.contrib.postgres.aggregates.JSONBAgg, but different.
- Supports both Postgres (JSONB_AGG) and MySQL (JSON_ARRAYAGG)
- Does not support
ordering
as JSON_ARRAYAGG does not guarantee ordering.
Source code in nautobot/core/models/query_functions.py
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.
Source code in nautobot/core/models/name_color_content_types.py
nautobot.apps.models.NaturalOrderingField
¶
Bases: models.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)
Source code in nautobot/core/models/fields.py
pre_save(model_instance, add)
¶
Generate a naturalized value from the target field
Source code in nautobot/core/models/fields.py
nautobot.apps.models.NotesMixin
¶
Adds a notes
property that returns a queryset of Notes
membership.
Source code in nautobot/extras/models/mixins.py
notes
property
¶
Return a Notes
queryset for this instance.
get_notes_url(api=False)
¶
Return the notes URL for a given instance.
Source code in nautobot/extras/models/mixins.py
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.
Source code in nautobot/core/models/generics.py
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.
Source code in nautobot/core/models/generics.py
nautobot.apps.models.RelationshipModel
¶
Bases: models.Model
Abstract class for any model which may have custom relationships associated with it.
Source code in nautobot/extras/models/relationships.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
get_relationships(include_hidden=False, advanced_ui=None)
¶
Return a dictionary of RelationshipAssociation querysets for all custom relationships
Returns:
Type | Description |
---|---|
dict
|
|
Source code in nautobot/extras/models/relationships.py
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 code in nautobot/extras/models/relationships.py
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
Source code in nautobot/extras/models/relationships.py
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
Source code in nautobot/extras/models/relationships.py
required_related_objects_errors(output_for='ui', initial_data=None, relationships_key_specified=False, instance=None)
classmethod
¶
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:
Type | Description |
---|---|
list[dict]
|
List of field error dicts if any are found |
Source code in nautobot/extras/models/relationships.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
nautobot.apps.models.RestrictedQuerySet
¶
Bases: CompositeKeyQuerySetMixin
, QuerySet
Source code in nautobot/core/models/querysets.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
|
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 |
self.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 |
Source code in nautobot/core/models/querysets.py
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 |
Source code in nautobot/core/models/querysets.py
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'
Source code in nautobot/core/models/querysets.py
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
)
Source code in nautobot/extras/models/statuses.py
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.
Source code in nautobot/extras/models/statuses.py
nautobot.apps.models.StatusModel
¶
Bases: models.Model
Deprecated abstract base class for any model which may have statuses.
Just directly include a StatusField instead for any new models.
Source code in nautobot/extras/models/statuses.py
nautobot.apps.models.TagsField
¶
Bases: TaggableManager
Override FormField method on taggit.managers.TaggableManager to match the Nautobot UI.
Source code in nautobot/core/models/fields.py
nautobot.apps.models.TagsManager
¶
Bases: _TaggableManager
, BaseManager
Manager class for model 'tags' fields.
nautobot.apps.models.TreeManager
¶
Bases: TreeManager_
, BaseManager.from_queryset(TreeQuerySet)
Extend django-tree-queries' TreeManager to incorporate RestrictedQuerySet.
Source code in nautobot/core/models/tree_queries.py
nautobot.apps.models.TreeModel
¶
Bases: TreeNode
Nautobot-specific base class for models that exist in a self-referential tree.
Source code in nautobot/core/models/tree_queries.py
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_
, querysets.RestrictedQuerySet
Combine django-tree-queries' TreeQuerySet with our RestrictedQuerySet for permissions enforcement.
Source code in nautobot/core/models/tree_queries.py
max_tree_depth()
¶
Get the maximum depth of any tree in this queryset.
Source code in nautobot/core/models/tree_queries.py
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.
Source code in nautobot/core/models/validators.py
nautobot.apps.models.VarbinaryIPField
¶
Bases: models.BinaryField
IP network address
Source code in nautobot/ipam/fields.py
db_type(connection)
¶
Returns the correct field type for a given database vendor.
Source code in nautobot/ipam/fields.py
from_db_value(value, expression, connection)
¶
get_db_prep_value(value, connection, prepared=False)
¶
Converts Python (str) to DB (varbinary).
Source code in nautobot/ipam/fields.py
to_python(value)
¶
value_to_string(obj)
¶
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"
Source code in nautobot/core/models/utils.py
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()
.
Source code in nautobot/core/models/utils.py
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.
Source code in nautobot/core/models/utils.py
nautobot.apps.models.count_related(model, field)
¶
Return a Subquery suitable for annotating a child object count.
Source code in nautobot/core/models/querysets.py
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 PythonNone
.
Inverse operation of construct_composite_key()
.
Source code in nautobot/core/models/utils.py
nautobot.apps.models.extras_features(*features)
¶
Decorator used to register extras provided features to a model
Source code in nautobot/extras/utils.py
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.
Source code in nautobot/core/models/utils.py
nautobot.apps.models.get_all_concrete_models(base_class)
¶
Get a list of all non-abstract models that inherit from the given base_class.
Source code in nautobot/core/models/utils.py
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)
Source code in nautobot/core/models/ordering.py
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.
Source code in nautobot/core/models/ordering.py
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') ) ) )
Source code in nautobot/core/models/utils.py
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.
Source code in nautobot/core/models/utils.py
nautobot.apps.models.serialize_object_v2(obj)
¶
Return a JSON serialized representation of an object using obj's serializer.
Source code in nautobot/core/models/utils.py
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