13

私は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 newthing in newthings_list%} {{newthing.to_add}} {%end%}

TL; DR:基本的に、データベースからデータのリストを取得したいので、このオブジェクトのリストに、計算値を含むフィールドを追加します。

不明な点がある場合はお知らせください。phpからdjangohahaに切り替えるのに苦労しています。

ありがとう!

編集:

だから、私は辞書で試していますが、ロジックが欠けているに違いありません:

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

ありがとう!

4

3 に答える 3

41

Pythonオブジェクトには何でも設定できます。

for obj in self.model.objects.all() :
    obj.score = total_score / total_posts

これは、objにscore属性がない場合でも機能します。テンプレートでは、次のようにリクエストします。

{{ obj.score }}

はい、それはとても簡単です。ただし、実行している計算をデータベースで実行できる場合は、注釈を調べる必要があります。

于 2012-08-26T11:58:24.007 に答える
3

辞書を使ってみませんか?

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

テンプレートでは、次のコマンドでディクショナリ値にアクセスできます。

{{newthing.your_key}}

または、辞書の辞書がある場合はforループを使用します

于 2012-08-25T03:59:22.823 に答える
1

@Melvynのソリューションが機能しない場合:

.all()クエリセットを変更するときにクエリセットでetcを呼び出さないようにしてください.all()。たとえば、クエリセットのコピーが返されます。

qs = foo.objects.filter(bar=1); 
for obj in qs.all(): 
    obj.caz = 1;  # Will not persist

これqsで変更はありません。

それよりも:

qs = foo.objects.filter(bar=1).all(); 
for obj in qs: 
    obj.caz = 1; 

.cazこれで、テンプレートにアクセスできます。

于 2021-09-08T19:34:47.157 に答える