Django - 向queryset添加字段以存储计算结果

Alb*_*lla 8 django list append

我是Django的新手,来自PHP世界.我正在尝试在计算事物后向查询集添加一个字段,并且不知道该怎么做.在PHP中,我只需在数组中添加一列并将其中的内容存储在其中.

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

所以基本上在我的模板中,我希望能够致电:{%for newthing in newthings_list%} {{newthing.to_add}} {%end%}

TL; DR:我基本上想从我的数据库中检索一个东西列表,并在这个对象列表中添加一个包含计算值的字段.

让我知道,如果不清楚,我很难从PHP切换到django哈哈.

谢谢!

编辑:

所以,我正在尝试使用dictionnary,但我必须忽略逻辑:

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
Run Code Online (Sandbox Code Playgroud)

然后当我开始工作时,我不知道如何在模板中访问它:

 {% for id in my_list %}
     {{newthing[id]}} ? Or something like newthing.id ?
 {% end %}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mel*_*vyn 32

你可以在python对象上设置任何东西:

for obj in self.model.objects.all() :
    obj.score = total_score / total_posts
Run Code Online (Sandbox Code Playgroud)

即使obj没有得分属性,这也会有效.在模板请求中它是这样的:

{{ obj.score }}
Run Code Online (Sandbox Code Playgroud)

是的,就这么简单.但是,如果您正在进行的计算可以在数据库中完成,那么您应该查看注释.


sma*_*ang 3

为什么不使用字典呢?

newthing = {}
newthing['your_key'] = to_add
Run Code Online (Sandbox Code Playgroud)

在模板中,您可以通过以下方式访问字典值:

{{newthing.your_key}}
Run Code Online (Sandbox Code Playgroud)

或者如果你有字典的字典,则使用 for 循环