from django.db import models

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

    def __str__(self):
        return "Q: %s " % self.question

    class Meta:
        db_table = 'poll'

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

    def __str__(self):
        return "Choice: %s in poll %s" % (self.choice, self.poll)

    class Meta:
        db_table = 'poll_choices'

__test__ = {'API_TESTS':"""
# Regression test for the use of .group_by() on querysets.
# Set up some initial polls and choices
>>> p1 = Poll(question='Why?')
>>> p1.save()
>>> c1 = Choice(poll=p1, choice='Because.')
>>> c1.save()
>>> c2 = Choice(poll=p1, choice='Why Not?')
>>> c2.save()
>>> c3 = Choice(poll=p1, choice='Group by is useful.')
>>> c3.save()

# GROUP BY on poll_id should return 1 result
>>> Choice.objects.all().group_by('poll').count()
1

# .group_by() does not support DESC (only MySQL does) so it fails
# because -poll is an invalid column name
>>> Choice.objects.all().group_by('-poll')
Traceback (most recent call last):
...
OperationalError: no such column: poll_choices.-poll

# GROUP BY on poll_id with a COUNT() should return the number of choices
>>> Poll.objects.all().extra(select={'choice_count': 'COUNT(`poll_choices`.`id`)'}, tables=['`poll_choices`'], where=['`poll_choices`.`poll_id` = `poll`.`id`']).group_by('id').get().choice_count
3
"""}

