2006-05-02 01:31:56 +00:00
|
|
|
"""
|
2006-05-31 19:23:07 +00:00
|
|
|
28. Many-to-many and many-to-one relationships to the same table
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2006-05-31 19:23:07 +00:00
|
|
|
Make sure to set ``related_name`` if you use relationships to the same table.
|
2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class User(models.Model):
|
|
|
|
username = models.CharField(maxlength=20)
|
|
|
|
|
|
|
|
class Issue(models.Model):
|
|
|
|
num = models.IntegerField()
|
|
|
|
cc = models.ManyToManyField(User, blank=True, related_name='test_issue_cc')
|
|
|
|
client = models.ForeignKey(User, related_name='test_issue_client')
|
2006-05-31 19:23:07 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.num)
|
2006-05-31 19:10:43 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class Meta:
|
|
|
|
ordering = ('num',)
|
|
|
|
|
|
|
|
|
|
|
|
API_TESTS = """
|
|
|
|
>>> Issue.objects.all()
|
|
|
|
[]
|
|
|
|
>>> r = User(username='russell')
|
|
|
|
>>> r.save()
|
|
|
|
>>> g = User(username='gustav')
|
|
|
|
>>> g.save()
|
2006-07-11 03:20:11 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> i = Issue(num=1)
|
|
|
|
>>> i.client = r
|
|
|
|
>>> i.save()
|
2006-07-11 03:20:11 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> i2 = Issue(num=2)
|
|
|
|
>>> i2.client = r
|
|
|
|
>>> i2.save()
|
|
|
|
>>> i2.cc.add(r)
|
2006-07-11 03:20:11 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> i3 = Issue(num=3)
|
|
|
|
>>> i3.client = g
|
|
|
|
>>> i3.save()
|
|
|
|
>>> i3.cc.add(r)
|
2006-07-11 03:20:11 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> from django.db.models.query import Q
|
2006-07-11 03:20:11 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(client=r.id)
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 1>, <Issue: 2>]
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(client=g.id)
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 3>]
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(cc__id__exact=g.id)
|
|
|
|
[]
|
|
|
|
>>> Issue.objects.filter(cc__id__exact=r.id)
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 2>, <Issue: 3>]
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2006-07-11 03:20:11 +00:00
|
|
|
# These queries combine results from the m2m and the m2o relationships.
|
|
|
|
# They're three ways of saying the same thing.
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id))
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 1>, <Issue: 2>, <Issue: 3>]
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id)
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 1>, <Issue: 2>, <Issue: 3>]
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id))
|
2006-06-01 04:30:39 +00:00
|
|
|
[<Issue: 1>, <Issue: 2>, <Issue: 3>]
|
2006-05-02 01:31:56 +00:00
|
|
|
"""
|