from django.db import models

class Page(models.Model):
    name = models.CharField(maxlength=100)

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    page = models.ForeignKey(Page)

    class Meta:
        db_table = 'poll'

class Choice(models.Model):
    poll = models.ForeignKey(Poll, related_name="choices")
    choice = models.CharField(maxlength=200)

    class Meta:
        db_table = 'poll_choices'

__test__ = {'API_TESTS':"""
# Regression test for the use of .select_related() on querysets.
# Set up some initial models
>>> from django.db import connection
>>> s1 = Page.objects.create(name="Hi")
>>> p1 = Poll.objects.create(question='Why?', page=s1)
>>> p2 = Poll.objects.create(question='Why 2?', page=s1)
>>> p3 = Poll.objects.create(question='Why 3?', page=s1)
>>> p4 = Poll.objects.create(question='Why 4?', page=s1)
>>> c1 = Choice.objects.create(poll=p1, choice='Because.')
>>> c2 = Choice.objects.create(poll=p1, choice='Why Not?')
>>> c3 = Choice.objects.create(poll=p1, choice='Group by is useful.')

# select_related(depth=1) shouldn't cause us extra queries
>>> z = Choice.objects.all().select_related(depth=1).order_by('id')
>>> q = len(connection.queries)
>>> z[0].poll
<Poll: Poll object>
>>> len(connection.queries)-q
0

# select_related('poll') shouldn't cause us extra queries
>>> z = Choice.objects.all().select_related('poll').order_by('id')
>>> q = len(connection.queries)
>>> z[0].poll
<Poll: Poll object>
>>> len(connection.queries)-q
0

# select_related('poll__page') shouldn't cause us extra queries
>>> z = Choice.objects.all().select_related('poll__page').order_by('id')
>>> q = len(connection.queries)
>>> z[0].poll.page
<Page: Page object>
>>> len(connection.queries)-q
0

# verify it's joining on the right table
>>> Choice.objects.all().select_related('poll').order_by('id')[0:1].get().poll.question
'Why?'

# should raise FieldDoesNotExist exception
>>> Choice.objects.all().select_related('wtf').order_by('id')
Traceback (most recent call last):
...
FieldDoesNotExist: Choice has no field named wtf
"""}
