Home > Software engineering >  In Django define a validation function to avoid number overlaps
In Django define a validation function to avoid number overlaps

Time:08-24

In django apps i have a model for the range number

In my model.py

def valide_range(value):
   all_ranges = RangeNumber.objects.all()
   for a_range in all_ranges:
       if a_range.start_num_int <= value <= a_range.end_num_int:
           raise ValidationError('The number is in an exiting number range')


class RangeNumber(models.Model):
   start_num = models.IntegerField(validators=[valide_range])
   end_num = models.IntegerField(validators=[valide_range])

This validation is ok for the create range but not for the udapte range, because is check all range(the edited range and the other), for the update I want just check the other.

Thanks


CodePudding user response:

You can use clean() in the model, and exclude the record if has the pk (if its saved in the db) - warning untested code:

from django.db.models import Q

def clean(self):
    cleaned_data = super().clean()
    start_num = cleaned_data.get("start_num")
    end_num = cleaned_data.get("end_num")
    
    q = Q()
    if self.pk:
        Q(id=self.pk)

    all_ranges = RangeNumber.objects.exclude(q)
    for a_range in all_ranges:
        if a_range.start_num_int <= start_num <= a_range.end_num_int:
            raise ValidationError('The number is in an exiting number range')
        if a_range.start_num_int <= end_num <= a_range.end_num_int:
            raise ValidationError('The number is in an exiting number range')

CodePudding user response:

@lorenzo Prodon

It works with :

def clean(self): 
    start_num = self.start_num if self.start_num else 0
    end_num = self.end_num if self.end_num else 0
    id = self.id if self.id else None
    
    all_ranges = RangeNumber.objects.exclude(id=f'{id}')

    for a_range in all_ranges:
        if a_range.start_num <= start_num <= a_range.end_num:
                raise ValidationError('The number is in an exiting number range')
            if a_range.start_num <= end_num_int <= a_range.end_num:
                raise ValidationError('The number is in an exiting number range')

I don't understand :

q = Q() <--- This ?
if self.pk:
  Q(id=self.pk)

and With cleaned_data = super().clean() is None ?

thanks

  • Related