Skip to content
Advertisement

Django model saves when it shouldn’t

I’m trying to set custom validation rules on my Django models. I have the following code:
Entity.py

JavaScript

Security.py

JavaScript

What I’m trying to do is to prevent a Security from being saved if its field entities holds more than 1 company. The entities field is a ManyToMany relationship with Entity, as it can hold multiple Asset objects but only one Company.
This is my test file

JavaScript

I tried with the Django shell and I have the same behaviour. The record gets saved even though I raise an exception in the save method, which doesn’t seem logical.
Would anyone know why ? What am I doing wrong, and how I could I avoid saving based on conditions?

Advertisement

Answer

I actually found the solution, thanks to Williem’s comment.
The m2m relation isn’t managed by save(), add(...) does it. So what did the trick is this function:

JavaScript
Advertisement