From 62b3d8f615c8464ff4b468ea7026b6ec3ac9a993 Mon Sep 17 00:00:00 2001 From: Martin Hauser Date: Wed, 20 May 2026 15:01:25 +0200 Subject: [PATCH] docs(customization): Add model validation guidance for Custom Scripts Adds warning and examples for validating NetBox objects before saving in Custom Scripts. Direct ORM writes bypass UI/API validation and can introduce invalid data. Recommends calling `full_clean()` explicitly. Fixes #22249 --- docs/customization/custom-scripts.md | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/customization/custom-scripts.md b/docs/customization/custom-scripts.md index cd6269a7c..62cbdfd88 100644 --- a/docs/customization/custom-scripts.md +++ b/docs/customization/custom-scripts.md @@ -220,6 +220,38 @@ class DeviceConnectionsReport(Script): self.log_success("Passed", device) ``` +## Model Validation + +!!! warning "Validate objects before saving" + Direct ORM writes bypass validation normally performed by NetBox's UI and REST API. + +Custom scripts can create and update NetBox objects directly through Django's ORM. When doing so, instantiate the model, call `full_clean()`, and then call `save()`: + +```python +obj = SomeModel( + field_a=value_a, + field_b=value_b, +) + +obj.full_clean() +obj.save() +``` + +Avoid using `Model.objects.create()` unless you intentionally want to skip model validation: + +```python +SomeModel.objects.create( + field_a=value_a, + field_b=value_b, +) +``` + +Django does not call `full_clean()` automatically when saving a model instance. Skipping validation can allow invalid or inconsistent data to be written to the database, which may later result in UI, API, or script errors. + +Bulk and direct queryset operations such as `bulk_create()`, `bulk_update()`, and `QuerySet.update()` should be used with the same care. These operations can bypass model validation and other model-specific save behavior. + +When editing an existing object, also see the change logging guidance below. + ## Change Logging To generate the correct change log data when editing an existing object, a snapshot of the object must be taken before making any changes to the object.