Nurhonov
Nurhonov

Reputation: 13

Django ManyToMany validation in model layer

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

Upvotes: 1

Views: 430

Answers (1)

Roham
Roham

Reputation: 2110

This error is saying that you are trying to access a Many2Many relation before saving your object in the database (i.e. without ID/PK). Unfortunately you can't access this Many2Many relation from your field in clean method when you didn't save your object in the database. Because these kind of objects (Many2Many) will be added to your instance after you create your objects. Since Django needs to query your through model based on your current instance, and when there isn't any instance it can not make a query for it and that is the main reason why it is raising error.

Basically you can not have access to objects' Many2Many relation (without ID/PK or before saving your new instance) in model's layer validators.

Upvotes: 1

Related Questions