Django - 将字段添加到查询集以存储计算结果

标签 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)

所以基本上在我的模板中,我希望能够调用:
{% for newthings_list %}
{{ newthing.to_add }}
{% 结束 %}

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

如果不清楚,请告诉我,我很难从 php 切换到 django 哈哈。

谢谢!

编辑:

所以,我正在尝试使用字典,但我必须错过逻辑:
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

然后当我开始工作时,我不知道如何在模板中访问它:
 {% for id in my_list %}
     {{newthing[id]}} ? Or something like newthing.id ?
 {% end %}

谢谢!

最佳答案

为什么不使用字典?

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

在模板中,您可以通过以下方式访问字典值:
{{newthing.your_key}}

或者,如果您有字典,请使用 for 循环

关于Django - 将字段添加到查询集以存储计算结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118776/

相关文章:

java - 在 Java 中使用字符串缓冲区进行字符串追加

unix - 可 append 的压缩文件

python - 将 OpenCV 与 Django 结合使用

Django 文件上传大小限制

python:如何从列表中打印单独的行?

python - 如何使用python查找列表中最大数字出现的次数?

windows - 在目录/子目录中生成文件夹 list.txt 文件,并在批处理文件中使用 dir & ren 命令将 list.txt 重命名为文件夹/子文件夹名称

python - Excel 工作簿到 html Django/Python

Python/Django : Cannot import GeoIP

python - 我有一个列表,其中包含更多字典,想要删除其中一个,但该字典是动态的