views:

33

answers:

1

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.

+2  A: 

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!

Dan Wolchonok
That's the right way of doing it: http://docs.djangoproject.com/en/1.2/ref/forms/api/#bound-and-unbound-forms
ars