Django - Add field to queryset to store computation results
You can set anything on a python object:
for obj in self.model.objects.all() : obj.score = total_score / total_posts
This will work even if obj does not have a score attribute. In the template request it like so:
{{ obj.score }}
Yes, it's that simple.However, if the calculations you're doing can be done in the database, you should look into annotate.
If @Melvyn's solution doesnt work for you:
Ensure you don't call .all()
etc on the queryset when modifying the queryset, as .all()
returns a copy of the queryset, e.g.
qs = foo.objects.filter(bar=1); for obj in qs.all(): obj.caz = 1; # Will not persist
Now qs
will remain unchanged.
Rather:
qs = foo.objects.filter(bar=1).all(); for obj in qs: obj.caz = 1;
Now you can access .caz
in the template.