Django - adding a field to the request to store the results of calculations

I am new to Django and come from the world of PHP. I am trying to β€œadd” a field to a query set after computing things and don’t know how to do it. In PHP, I would just add a column to the array and store my stuff in it.

Here is my code:

def (id): mystuff_details = mystuff_details.objects.filter(stuff_id=id) newthing = ''; for mystuff in mystuff_details: newthing_lists = //some query to get another queryset for newthing_list in newthing_lists: newthing = newthing_list.stuffIwant //Here I want to make some computation, and ADD something to newthing, let say: to_add = (mystuff.score+somethingelse) //I've heard about the .append but I'm sure I'm screwing it up newthing.append(to_add) 

So basically in my template I would like to call: {% for newthing in newthings_list%} {{newthing.to_add}} {% end%}

TL DR: I basically want to get a list of things from my database, and in this list of ADD objects there is a field that will contain the calculated value.

Let me know if this is unclear, it's hard for me to switch from php to django haha.

Thanks!

EDIT:

So, I'm trying to use dictionnary, but I miss the logic:

 def (id): mystuff_details = mystuff_details.objects.filter(stuff_id=id) newthing = {}; for mystuff in mystuff_details: newthing_lists = //some query to get another queryset for newthing_list in newthing_lists: //Newthing_list can have several times the same I, and the scores need to add up if newthing[newthing_list.id] > 0: //This doesn't seem to work and throws an error (KeyError) newthing[newthing_list.id] = newthing[newthing_list.id] + some_calculated_thing else: newthing[newthing_list.id] = some_calculated_thing 

And then, when I get this work, I don’t know how to access it in the template:

  {% for id in my_list %} {{newthing[id]}} ? Or something like newthing.id ? {% end %} 

Thanks!

+6
source share
2 answers

Why not use a dictionary?

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

In the template, you can access the dictionary values ​​with:

 {{newthing.your_key}} 

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

+3
source

You can install something 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 rating attribute. In the template request, it looks like this:

 {{ obj.score }} 

Yes, it is that simple. However, if your calculations can be performed in a database, you should study annotate .

+22
source

Source: https://habr.com/ru/post/923725/


All Articles