File: models.py

package info (click to toggle)
python-django 1.2.3-3%2Bsqueeze15
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 29,720 kB
  • ctags: 21,538
  • sloc: python: 101,631; xml: 574; makefile: 149; sh: 121; sql: 7
file content (59 lines) | stat: -rw-r--r-- 1,891 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
25. Reverse lookups

This demonstrates the reverse lookup features of the database API.
"""

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

class Poll(models.Model):
    question = models.CharField(max_length=200)
    creator = models.ForeignKey(User)

    def __unicode__(self):
        return self.question

class Choice(models.Model):
    name = models.CharField(max_length=100)
    poll = models.ForeignKey(Poll, related_name="poll_choice")
    related_poll = models.ForeignKey(Poll, related_name="related_choice")

    def __unicode__(self):
        return self.name

__test__ = {'API_TESTS':"""
>>> john = User(name="John Doe")
>>> john.save()
>>> jim = User(name="Jim Bo")
>>> jim.save()
>>> first_poll = Poll(question="What's the first question?", creator=john)
>>> first_poll.save()
>>> second_poll = Poll(question="What's the second question?", creator=jim)
>>> second_poll.save()
>>> new_choice = Choice(poll=first_poll, related_poll=second_poll, name="This is the answer.")
>>> new_choice.save()

>>> # Reverse lookups by field name:
>>> User.objects.get(poll__question__exact="What's the first question?")
<User: John Doe>
>>> User.objects.get(poll__question__exact="What's the second question?")
<User: Jim Bo>

>>> # Reverse lookups by related_name:
>>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
<Poll: What's the first question?>
>>> Poll.objects.get(related_choice__name__exact="This is the answer.")
<Poll: What's the second question?>

>>> # If a related_name is given you can't use the field name instead:
>>> Poll.objects.get(choice__name__exact="This is the answer")
Traceback (most recent call last):
    ...
FieldError: Cannot resolve keyword 'choice' into field. Choices are: creator, id, poll_choice, question, related_choice
"""}