0

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?

rantanplan
  • 7,283
  • 1
  • 24
  • 45
zVictor
  • 3,610
  • 3
  • 41
  • 56

2 Answers2

1

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.

rantanplan
  • 7,283
  • 1
  • 24
  • 45
0

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.

Community
  • 1
  • 1
zVictor
  • 3,610
  • 3
  • 41
  • 56
  • This makes sense only if you want to hook it against django models you don't control(e.g. django built-in models). Or you want to subscribe many actions on this specific event. Not for what you asked. – rantanplan May 18 '12 at 16:04