Create an instance that represents the average of multiple instances

I have a Review Model like the one defined below (I removed a bunch of the fields in REVIEW_FIELDS). I want to find the average of a subset of the attributes and populate a ModelForm with the computed information.

REVIEW_FIELDS = ['noise']

class Review(models.Model):
  notes = models.TextField(null=True, blank=True)

  CHOICES = ((1, u'Quiet'), (2, u'Kinda Quiet'), (3, u'Loud'))
  noise = models.models.IntegerField('Noise Level', blank-True, null=True, choices=CHOICES)

class ReviewForm(ModelForm):

  class Meta:
    model = Review
    fields = REVIEW_FIELDS

I can easily add more fields to the model, and then add them to the REVIEW_FIELDS list. Then I can easily iterate over them in javascript, etc. In my view, I want to compute the average of a bunch of the integer fields and populate a ReviewForm with the attribute values. How can I do something like this?

stats = {}
for attr in REVIEW_FIELDS:
  val = reviews.aggregate(Avg(attr)).values()[0]
  if val:
    stats[attr] = int(round(val,0))
    r.attr = stats[attr]
r = Review()
f = ReviewForm(r)

How can I create a ReviewForm with the average values without hard-coding the attribute values? I'd like to be able to add the field, add the value to the list, and have it automatically added to the set of statistics computed.

If I'm doing something fundamentally wrong, please let me know. I'm relatively new to django, so I might be re-inventing functionality that already exists.


After looking at the docs, I pass a dictionary to the ReviewForm when instantiating it:

f = ReviewForm(stats)

It seems to work pretty well! If anyone has any suggestions on a better way to do this, I'm all ears!

Need Your Help

Python re match at specific point in string

python regex

If I have a given string s in Python, is it possible to easily check if a regex matches the string starting at a specific position i in the string?

Jekyll for loop - multiple arrays


In Jekyll, I have a small blog system going with two categories: blog and portfolio. I have two pages that will render the posts for these categories, with a for loop that looks something like this...