Is it important to use full_clean? #14718
-
|
I'm learning how to write Netbox custom scripts, trying to do things "the right way". from django.core.exceptions import ValidationError
try:
ip = IPAddress(address='???')
ip.save()
except ValidationError as e:
self.log_failure(e)
continueThis works well, and if the IP address is invalid I get a nice error message like: But then I found some posts suggesting to use try:
ip = IPAddress(address='???')
ip.full_clean()
ip.save()
except AttributeError as e:
self.log_failure(e)
continueException: I prefer my first approach, and the documentation isn't super clear about this. Is there any important reason to do the full_clean before save? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
|
The reason the first way of doing it is raising a ValidationError is an edgecase as the custom field type netbox uses for that field does validation when converting values: Line 35 in c78a792 In general, when not running full_clean, none of the following methods are run:
https://docs.djangoproject.com/en/5.0/ref/models/instances/#django.db.models.Model.full_clean You have to always call full_clean, as this is how it works both in the API and the UI. Not doing so will allow you to corrupt various data. The reason your second example fails is because the clean method itself expects a proper ip address object with the prefixlen attribute and as such throws an exeception when validating the data: netbox/netbox/ipam/models/ip.py Line 842 in c78a792 This is technically a bug, but I wouldn't expect it being fixed.
Short answer, yes to avoid corrupt data. |
Beta Was this translation helpful? Give feedback.
-
|
I forgot to mention: a specific requirement in Netbox is that you also need to call (IMO it would be more robust if this could be implemented using Postgres triggers - or alternatively if the application moved to a full event sourcing architecture, i.e. the current state tables are built entirely from the event log) |
Beta Was this translation helpful? Give feedback.
The reason the first way of doing it is raising a ValidationError is an edgecase as the custom field type netbox uses for that field does validation when converting values:
netbox/netbox/ipam/fields.py
Line 35 in c78a792
In general, when not running full_clean, none of the following methods are run:
https://docs.djangoproject.com/en/5.0/ref/models/instances/#django.db.models.Model.full_clean
You have to always call full_clean, as this is how it works both in the API and the UI. Not doing…