Modeling django model statistics

1.7k Views Asked by At

I'm working on a questionnaire model for django that should be maintainable by someone with no programming experience, so I've spent a lot of time crafting my models to compensate for minor details.. Now I want to unlock the potential of SQL database queries to be able to generate statistics about the responses and feedback given.

One of my question types is a 5 star rating, so I would like to be able to gather statistics about the question like:

  • How many responses for question q were 5 star (, 4star, 3star, etc.)?
  • What was the average rating response?

Ideally I would like to record these statistic questions in a model, and create a view that shows all the statistics asked and keep the entire thing programmatic.

Should this be a carefully crafted model or set of models like feedback, or is there already some framework or module that handles these situations for me?

My questionnaire/models.py:

class QuestionType(models.Model):
    name = models.CharField(max_length=256, blank=True, default="")

class Question(models.Model):
    text = models.TextField()
    type = models.ForeignKey(QuestionType)

class Response(models.Model):
    question = models.ForeignKey(Question)
    answer = models.TextField()

class Feedback(models.Model):
    user = models.ForeignKey(User)
    responses = models.ManyToManyField(Response)
    response_time = models.DateTimeField(auto_now_add=True)
1

There are 1 best solutions below

1
On

This would cover your requirements:

class QuestionType(models.Model):
    name = models.CharField(max_length=256, blank=True, default="")

class Question(models.Model):
    text = models.TextField()
    type = models.ForeignKey(QuestionType)

    def how_many_ratings_where_x_stars(self, stars):
        return self.rating_set.filter(stars=stars).count()

    def average_rating(self, stars):
        return self.rating_set.aggregate(models.Avg('stars'))['stars__avg']

class Response(models.Model):
    question = models.ForeignKey(Question)
    answer = models.TextField()
    user = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add=True)

class Rating(models.Model):
    question = models.ForeignKey(Question)
    stars = models.PositiveIntegerField(min_value=1, max_value=5)
    user = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = [('question', 'user')]