Idiomatic way to perform atomic, DB-data-based validation before save

How should one perform DB-data-based, data validation atomically before saving?

The validator function validates single-field data, and the clean method validates single-object data.
But in case data should be verified along with existing data on DB.

For example, say making an acyclic linked list with the Django model.
Linking could be represented by ForeignKeyField, but the acyclicity should be check with pre-existing data on the DB and it should be atomic.

What would be an idiomatic way to perform these kinds of validation? (Of course, should also work on admin pages)

One posibility is the clean method on the model (docs).

I canā€™t find any mention of atomicity about the clear method in the official documentation. Is it atomic? I think there should be at least a write-lock on the relevant data before reading data for validation and until the save or termination.

That was the validation part. Checkout the transaction.atomic decorator.

Okay, it says transaction.atomic decorator makes ā€˜a block of codeā€™ atomic. Which means one can use the decorator for the save method right?

Yeah, you can use the decorator on any function.

So, just one last check, Itā€™s possible and also an idiomatic way to do these kinds of validation for DB integrity, right? (Locking the DB and performing some query, do the validation, and save if ok. , kinds of things)

The clean method is a good candidate as i said before.
It integrates well with the admin too. You just have to remember calling full_clean before save.

I am really sorry, but trying to learn I have to askā€¦ Atomic, clean vs full_clean, validation.
Would one of you please elaborate a bit? (please dumb it down for me) :grin:

Atomic:
Decorator that wraps a function and will create a database transaction, commiting the transaction on exiting the function if no exceptions were raised, if exceptions were raised then rollback the transaction. This is really useful if a function is creating modifying a lot of resources.

Clean & Full clean & Validation:
The clean method is a ā€œhookā€ that can be defined on every model that will make shore that the instance is clean, if the instance is dirty (contains bad data) it them should raise a ValidationError. This is used by the admin, and itā€™s really useful to do some short validation on data on the instance itself before saving to the database. Example:

user = User()
user.username = None  # this is not valid
user.full_clean() # will raise a validation error
1 Like

Thank you so much @leandrodesouzadev :muscle: