Code

Ticket #6778: models.py

File models.py, 1.8 KB (added by mysliceof314, 6 years ago)

model tests for the m2m signals

Line 
1"""
2Testing signals fired when item(s) are added to a many-to-many relation,
3when items are removed and when the relation is cleared
4"""
5print('testing m2m signals')
6
7from django.db import models
8from django.db.models import signals
9
10class Pizza(models.Model):
11    name = models.CharField(max_length=60)
12
13class Topping(models.Model):
14    name = models.CharField(max_length=50)
15    pizzas = models.ManyToManyField(Pizza) 
16
17def 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
21def 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   
25signals.m2m_related_data_added.connect(relation_made)
26signals.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)
42veggie just associated with ['cheese', 'red pepper', 'mushrooms']
43>>> p2.topping_set.add(t1)
44cheese just associated with ['cheese']
45>>> p3.topping_set.add(t1,t3,t4)
46pepperoni just associated with ['cheese', 'mushrooms', 'pepperoni']
47>>> p3.topping_set.remove(t3)
48pepperoni just disassociated with ['mushrooms']
49>>> p3.topping_set.clear()
50pepperoni just disassociated with ['cheese', 'pepperoni']
51>>> t1.pizzas.add(p3)
52cheese just associated with ['pepperoni']
53>>> t1.pizzas.clear()
54cheese just disassociated with ['veggie', 'cheese', 'pepperoni']
55"""}