1

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

Nurhonov
  • 13
  • 4

1 Answers1

1

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.

Roham
  • 1,970
  • 2
  • 6
  • 16
  • Thanks for reply. I undersood what you said. I was wondering is there a way to create validation in model layer? Cuz i want to add db seeder and i think the logic of saved data will be broken – Nurhonov Apr 22 '22 at 08:47
  • As I told before it is not possible to have validation on model layer for a Many2Many relation... However you can have some sort of validation on django forms or maybe serializer (based on your use case) with accessing it's data. For more information please take a look at https://stackoverflow.com/questions/7986510/django-manytomany-model-validation . – Roham Apr 25 '22 at 07:20