1 | """
|
---|
2 | Testing signals fired when item(s) are added to a many-to-many relation,
|
---|
3 | when items are removed and when the relation is cleared
|
---|
4 | """
|
---|
5 | print('testing m2m signals')
|
---|
6 |
|
---|
7 | from django.db import models
|
---|
8 | from django.db.models import signals
|
---|
9 |
|
---|
10 | class Pizza(models.Model):
|
---|
11 | name = models.CharField(max_length=60)
|
---|
12 |
|
---|
13 | class Topping(models.Model):
|
---|
14 | name = models.CharField(max_length=50)
|
---|
15 | pizzas = models.ManyToManyField(Pizza)
|
---|
16 |
|
---|
17 | def relation_made(signal, sender, **named):
|
---|
18 | names = str([str(x.name) for x in named['objs_added']])
|
---|
19 | print '%s just associated with %s' % (sender.name, names)
|
---|
20 |
|
---|
21 | def relation_unmade(signal, sender, **named):
|
---|
22 | names = str([str(x.name) for x in named['objs_removed']])
|
---|
23 | print '%s just disassociated with %s' % (sender.name, names)
|
---|
24 |
|
---|
25 | signals.m2m_related_data_added.connect(relation_made)
|
---|
26 | signals.m2m_related_data_removed.connect(relation_unmade)
|
---|
27 |
|
---|
28 | __test__ = {'API_TESTS':"""
|
---|
29 | >>> p1, p2, p3 = Pizza(name='veggie'), Pizza(name='cheese'), Pizza(name='pepperoni')
|
---|
30 | >>> p1.save()
|
---|
31 | >>> p2.save()
|
---|
32 | >>> p3.save()
|
---|
33 | >>> t1, t2, t3, t4= Topping(name='cheese'), Topping(name='red pepper'), \
|
---|
34 | Topping(name='mushrooms'), Topping(name='pepperoni')
|
---|
35 | >>> t1.save()
|
---|
36 | >>> t2.save()
|
---|
37 | >>> t3.save()
|
---|
38 | >>> t4.save()
|
---|
39 |
|
---|
40 | # associate some data
|
---|
41 | >>> p1.topping_set.add(t1,t2,t3)
|
---|
42 | veggie just associated with ['cheese', 'red pepper', 'mushrooms']
|
---|
43 | >>> p2.topping_set.add(t1)
|
---|
44 | cheese just associated with ['cheese']
|
---|
45 | >>> p3.topping_set.add(t1,t3,t4)
|
---|
46 | pepperoni just associated with ['cheese', 'mushrooms', 'pepperoni']
|
---|
47 | >>> p3.topping_set.remove(t3)
|
---|
48 | pepperoni just disassociated with ['mushrooms']
|
---|
49 | >>> p3.topping_set.clear()
|
---|
50 | pepperoni just disassociated with ['cheese', 'pepperoni']
|
---|
51 | >>> t1.pizzas.add(p3)
|
---|
52 | cheese just associated with ['pepperoni']
|
---|
53 | >>> t1.pizzas.clear()
|
---|
54 | cheese just disassociated with ['veggie', 'cheese', 'pepperoni']
|
---|
55 | """}
|
---|