"""
Testing signals fired when item(s) are added to a many-to-many relation, 
when items are removed and when the relation is cleared
"""
print('testing m2m signals')

from django.db import models
from django.db.models import signals

class Pizza(models.Model):
    name = models.CharField(max_length=60)

class Topping(models.Model):
    name = models.CharField(max_length=50)
    pizzas = models.ManyToManyField(Pizza)  

def relation_made(signal, sender, **named):
    names = str([str(x.name) for x in named['objs_added']])
    print '%s just associated with %s' % (sender.name, names)

def relation_unmade(signal, sender, **named):
    names = str([str(x.name) for x in named['objs_removed']])
    print '%s just disassociated with %s' % (sender.name, names)
    
signals.m2m_related_data_added.connect(relation_made)
signals.m2m_related_data_removed.connect(relation_unmade)

__test__ = {'API_TESTS':"""
>>> p1, p2, p3 = Pizza(name='veggie'), Pizza(name='cheese'), Pizza(name='pepperoni')
>>> p1.save()
>>> p2.save()
>>> p3.save()
>>> t1, t2, t3, t4= Topping(name='cheese'), Topping(name='red pepper'), \
                    Topping(name='mushrooms'), Topping(name='pepperoni')
>>> t1.save()
>>> t2.save()
>>> t3.save()
>>> t4.save()

# associate some data
>>> p1.topping_set.add(t1,t2,t3)
veggie just associated with ['cheese', 'red pepper', 'mushrooms']
>>> p2.topping_set.add(t1)
cheese just associated with ['cheese']
>>> p3.topping_set.add(t1,t3,t4)
pepperoni just associated with ['cheese', 'mushrooms', 'pepperoni']
>>> p3.topping_set.remove(t3)
pepperoni just disassociated with ['mushrooms']
>>> p3.topping_set.clear()
pepperoni just disassociated with ['cheese', 'pepperoni']
>>> t1.pizzas.add(p3)
cheese just associated with ['pepperoni']
>>> t1.pizzas.clear()
cheese just disassociated with ['veggie', 'cheese', 'pepperoni']
"""}
