[Fixed]-Django – Add field to queryset to store computation results

3👍

Why not use a dictionary?

newthing = {}
newthing['your_key'] = to_add

In the template, you can access dictionary values with:

{{newthing.your_key}}

Or use the for loop if you have a dictionary of dictionaries

👤smang

41👍

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.

1👍

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.

Leave a comment