Skip to content

Instantly share code, notes, and snippets.

@justinzane
Created August 7, 2012 22:11
Show Gist options
  • Save justinzane/3289905 to your computer and use it in GitHub Desktop.
Save justinzane/3289905 to your computer and use it in GitHub Desktop.
Histogram from django models
##### Assessor.models #####
class Question(models.Model):
text = models.TextField()
explanation = models.TextField()
class Choice(models.Model):
text = models.TextField()
is_correct = models.BooleanField(default=False)
question = models.ForeignKey(Question)
class Answer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
choice = models.ForeignKey(Choice)
##### Assessor.api.py #####
from django.contrib.auth.models import User
from Assessor.models import Answer, Choice, Question
from tastypie import Stuff
...
class AnswerHistogramResource(<WHAT HERE>)
def generate_histogram(self, request):
un = request.META['HTTP_X_USERNAME']
user = User.objects.get_by_natural_key(un)
answers = Answer.objects.filter(user=user)
histogram = {}
for a in answers:
if not a.question_id in histogram.keys():
histogram[a.question_id] = {'correct': 0, 'incorrect': 0}
if Choice.objects.get(pk=a.choice_id).is_correct:
histogram[a.question_id]['correct'] += 1
else:
histogram[a.question_id]['incorrect'] += 1
return histogram
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment