How to do validation on django's ManyRelatedManager?

252 views Asked by At

I would like to change the behavior, maybe overwriting, when I add an instance to a M2M relation, so that I could do something like this:

try:
    my_instance.one_field_set.add( another_instance )
except ValidationError:
    # do something

Is that possible?

2

There are 2 answers

0
rantanplan On

Yes but don't do it that way.

1) Use can use an explicit intermediate model for your M2M relationship and provide it with a custom manager in which you can replace the create method.

2) In my opinion though, the best way is to have on one of these models an instance method add_something which provides the necessary validation and exception-handling logic.

1
zVictor On

I found a similar question, that is not exactly what I wanted, but helps as a workaround.

@receiver(m2m_changed, sender=MyModel.my_field.through)
def check(sender, **kwargs):
    if kwargs['action'] == 'pre_add':
        add = AnotherModel.objects.filter(pk__in=kwargs["pk_set"]) # instances being added
        # your validation here...

Thanks to mamachanko on his question.