Django - Add field to queryset to store computation results

痞子三分冷 提交于 2020-03-17 07:21:09

问题


I'm pretty new to Django and come from the PHP world. I'm trying to 'add' a field to a queryset after computing things, and don't know how to do it. In PHP I would just add a column in an array and store my stuff in it.

Here's 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's 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'd like to be able to call: {% for newthing in newthings_list %} {{ newthing.to_add }} {% end %}

TL;DR: I basically want to retrieve a list of stuff from my database, and in this list of objects ADD a field that will contain a computed value.

Let me know if it's unclear, I'm having a hard time switching from php to django haha.

Thanks!

EDIT:

So, I'm trying with a dictionnary, but I must be missing 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'll get that working, 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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/12118776/django-add-field-to-queryset-to-store-computation-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!