I have model with manytomany field and the task is to make an validation in model layer. When i run this code, this error occurs:
ValueError at /admin/main/boss/add/ "<Boss: Senior>" needs to have a value for field "boss_id" before
In django docs i found that to use m2m field i need to create object.But i cant create model object without validation, which requires m2m field.
I did research and in every other cases they recommended to create validation in Form layer. But problem with this, is when i will create object in djangoadmin or with seeder, saved data can cause problems. So i decided to make validation in model layer. Here is my model:
class Position(models.Model):
pos_id = models.BigAutoField(primary_key = True)
pos_name = models.CharField(max_length=80)
level = models.IntegerField(default=1)
def __str__(self) -> str:
return self.pos_name
class Meta:
verbose_name = 'Position'
verbose_name_plural = 'Positions'
class Boss(models.Model):
boss_id = models.BigAutoField(primary_key=True)
boss_position = models.ForeignKey(Position, null=True, on_delete = CASCADE)
subordinates = models.ManyToManyField(Position,related_name='bosses')
def __str__(self) -> str:
return self.boss_position.pos_name
@property
def position(self):
return self.boss_position
def clean(self) -> None:
subordinates_list = self.subordinates.objects.all()
if self.boss_position in subordinates_list:
raise ValidationError(_('Boss cant be boss in his subordinate list'))
class Meta:
verbose_name = 'Boss'
verbose_name_plural = 'Bosses'
thanks in advance for your reply