The Nautobot Python Shell¶
Nautobot includes a Python management shell within which objects can be directly queried, created, modified, and deleted. To enter the shell, run the following command:
This will launch a lightly customized version of the built-in Django shell with all relevant Nautobot models pre-loaded. (If desired, the stock Django shell is also available by executing
lsmodels() will print a list of all available Nautobot models:
The Nautobot shell affords direct access to Nautobot data and function with very little validation in place. As such, it is crucial to ensure that only authorized, knowledgeable users are ever granted access to it. Never perform any action in the management shell without having a full backup in place.
Objects are retrieved from the database using a Django queryset. The base queryset for an object takes the form
<model>.objects.all(), which will return a (truncated) list of all objects of that type.
for loop to cycle through all objects in the list:
>>> for device in Device.objects.all(): ... print(device.name, device.device_type) ... ('TestDevice1', <DeviceType: PacketThingy 9000>) ('TestDevice2', <DeviceType: PacketThingy 9000>) ('TestDevice3', <DeviceType: PacketThingy 9000>) ('TestDevice4', <DeviceType: PacketThingy 9000>) ('TestDevice5', <DeviceType: PacketThingy 9000>) ...
To count all objects matching the query, replace
To retrieve a particular object (typically by its primary key or other unique field), use
In most cases, you will want to retrieve only a specific subset of objects. To filter a queryset, replace
filter() and pass one or more keyword arguments. For example:
Querysets support slicing to return a specific range of objects.
count() method can be appended to the queryset to return a count of objects rather than the full list.
Relationships with other models can be traversed by concatenating attribute names with a double-underscore. For example, the following will return all devices assigned to the tenant named "Pied Piper."
This approach can span multiple levels of relations. For example, the following will return all IP addresses assigned to a device in North America:
While the above query is functional, it's not very efficient. There are ways to optimize such requests, however they are out of scope for this document. For more information, see the Django queryset method reference documentation.
Reverse relationships can be traversed as well. For example, the following will find all devices with an interface named "em0":
Character fields can be filtered against partial matches using the
icontains field lookup (the later of which is case-insensitive).
Similarly, numeric fields can be filtered by values less than, greater than, and/or equal to a given value.
Multiple filters can be combined to further refine a queryset.
To return the inverse of a filtered queryset, use
exclude() instead of
The examples above are intended only to provide a cursory introduction to queryset filtering. For an exhaustive list of the available filters, please consult the Django queryset API documentation.
Creating and Updating Objects¶
New objects can be created by instantiating the desired model, defining values for all required attributes, and calling
validated_save() on the instance. For example, we can create a new VLAN by specifying its numeric ID, name, and assigned site:
Alternatively, the above can be performed as a single operation. (Note, however, that
validated_save() does not return the new instance for reuse.)
To modify an existing object, we retrieve it, update the desired field(s), and call
It is recommended to make use of the
validated_save() convenience method which exists on all core models. While the Django
save() method still exists, the
validated_save() method saves the instance data but first enforces model validation logic. Simply calling
save() on the model instance does not enforce validation automatically and may lead to bad data. See the development best practices.
The Django ORM provides methods to create/edit many objects at once, namely
update(). These are best avoided in most cases as they bypass a model's built-in validation and can easily lead to database corruption if not used carefully.
To delete an object, simply call
delete() on its instance. This will return a dictionary of all objects (including related objects) which have been deleted as a result of this operation.
To delete multiple objects at once, call
delete() on a filtered queryset. It's a good idea to always sanity-check the count of selected objects before deleting them.
Deletions are immediate and irreversible. Always consider the impact of deleting objects carefully before calling
delete() on an instance or queryset.
Change Logging and Webhooks¶
Note that Nautobot's change logging and webhook processing features operate under the context of an HTTP request. As such, these functions do not work automatically when using the ORM directly, either through the
nbshell or otherwise. A special context manager is provided to allow these features to operate under an emulated HTTP request context. This context manager must be explicitly invoked for change log entries and webhooks to be created when interacting with objects through the ORM. Here is an example using the
web_request_context context manager within the nbshell:
User object must be provided. A
WSGIRequest may optionally be passed and one will automatically be created if not provided.