Django-将字段添加到queryset以存储计算结果 [英] Django - Add field to queryset to store computation results

查看:664
本文介绍了Django-将字段添加到queryset以存储计算结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,来自PHP世界.我试图在计算完东西后将字段添加"到查询集中,但不知道该怎么做.在PHP中,我只需要在数组中添加一列并将其存储在其中即可.

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.

这是我的代码:

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)

因此基本上,在我的模板中,我希望能够调用: {%表示newthings_list%中的newthing} {{newthing.to_add}} {%end%}

So basically in my template I'd like to be able to call: {% for newthing in newthings_list %} {{ newthing.to_add }} {% end %}

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

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.

让我知道是否不清楚,我很难从php切换到django haha​​.

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

谢谢!

因此,我正在尝试使用词典,但我必须缺少逻辑:

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 %}

谢谢!

推荐答案

为什么不使用字典?

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

在模板中,您可以使用以下命令访问字典值:

In the template, you can access dictionary values with:

{{newthing.your_key}}

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

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

这篇关于Django-将字段添加到queryset以存储计算结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆