Search code examples
djangodjango-modelsdjango-signalsdjango-validation

Django Model validation based on a field value of another Model


I have this Django model:

   from accounts.models import Account
   

   class BankOperation(models.Model):
    
       created_at = models.DateTimeField(auto_now_add=True)
       account = models.ForeignKey(Account, on_delete=models.CASCADE)
       operation_import = models.FloatField(default=0.0)
    
    

I want to make sure that the operation_import is not higher than account.balance what is the official way to this? I have seen some answers talking about overriding the save() method but others advise against it.

should i add a pre-save signal and throw some kind of exception?

Is there a way to create a field validator that accepts parameters? so maybe something like:

   def validate_bank_operation_import(value, account_balance):

   if value > account_balance:

        raise ValidationError("Bank operation import is higher than account balance!")

and inside my model i change the field to:

operation_import = models.FloatField(default=0.0, validators=[validate_bank_operation_import])

But can i pass parameters to a validator? if yes, how do I do it?

perhaps there is another to do this validation!


Solution

  • Override clean on the model? The validation process is described in detail in the doc, which includes use of this method to implement custom validation. Since it's a bound method it has access to self and thence self.account.balance.