|
1 """ |
|
2 29. Many-to-many and many-to-one relationships to the same table |
|
3 |
|
4 Make sure to set ``related_name`` if you use relationships to the same table. |
|
5 """ |
|
6 |
|
7 from django.db import models |
|
8 |
|
9 class User(models.Model): |
|
10 username = models.CharField(maxlength=20) |
|
11 |
|
12 class Issue(models.Model): |
|
13 num = models.IntegerField() |
|
14 cc = models.ManyToManyField(User, blank=True, related_name='test_issue_cc') |
|
15 client = models.ForeignKey(User, related_name='test_issue_client') |
|
16 |
|
17 def __str__(self): |
|
18 return str(self.num) |
|
19 |
|
20 class Meta: |
|
21 ordering = ('num',) |
|
22 |
|
23 |
|
24 __test__ = {'API_TESTS':""" |
|
25 >>> Issue.objects.all() |
|
26 [] |
|
27 >>> r = User(username='russell') |
|
28 >>> r.save() |
|
29 >>> g = User(username='gustav') |
|
30 >>> g.save() |
|
31 |
|
32 >>> i = Issue(num=1) |
|
33 >>> i.client = r |
|
34 >>> i.save() |
|
35 |
|
36 >>> i2 = Issue(num=2) |
|
37 >>> i2.client = r |
|
38 >>> i2.save() |
|
39 >>> i2.cc.add(r) |
|
40 |
|
41 >>> i3 = Issue(num=3) |
|
42 >>> i3.client = g |
|
43 >>> i3.save() |
|
44 >>> i3.cc.add(r) |
|
45 |
|
46 >>> from django.db.models.query import Q |
|
47 |
|
48 >>> Issue.objects.filter(client=r.id) |
|
49 [<Issue: 1>, <Issue: 2>] |
|
50 >>> Issue.objects.filter(client=g.id) |
|
51 [<Issue: 3>] |
|
52 >>> Issue.objects.filter(cc__id__exact=g.id) |
|
53 [] |
|
54 >>> Issue.objects.filter(cc__id__exact=r.id) |
|
55 [<Issue: 2>, <Issue: 3>] |
|
56 |
|
57 # These queries combine results from the m2m and the m2o relationships. |
|
58 # They're three ways of saying the same thing. |
|
59 >>> Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id)) |
|
60 [<Issue: 1>, <Issue: 2>, <Issue: 3>] |
|
61 >>> Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id) |
|
62 [<Issue: 1>, <Issue: 2>, <Issue: 3>] |
|
63 >>> Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)) |
|
64 [<Issue: 1>, <Issue: 2>, <Issue: 3>] |
|
65 """} |