Sono piuttosto nuovo per Django e provengo dal mondo PHP. Sto cercando di "aggiungere" un campo a un queryset dopo aver calcolato le cose, e non so come farlo. In PHP vorrei solo aggiungere una colonna in un array e memorizzare le mie cose in esso.Django - Aggiungi il campo al queryset per archiviare i risultati del calcolo
Ecco il mio codice:
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)
Quindi, in pratica nel mio modello Mi piacerebbe essere in grado di chiamare: {% per newthing in% newthings_list} {{ newthing.to_add}} { % end%}
TL; DR: Fondamentalmente voglio recuperare un elenco di cose dal mio database e in questo elenco di oggetti ADD un campo che conterrà un valore calcolato.
Fammi sapere se non è chiaro, ho difficoltà a passare da php a django haha.
Grazie!
EDIT:
Quindi, sto cercando con un Dictionnary, ma devo essere manca la logica:
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
E poi, quando avrò che il lavoro, non lo so come accedervi nel modello:
{% for id in my_list %}
{{newthing[id]}} ? Or something like newthing.id ?
{% end %}
Grazie!
Ciao e grazie! Ho provato con i dizionari, questa è la parte dopo la "modifica" nella mia domanda, ma non ho avuto fortuna per ora. Cosa ho fatto di sbagliato nel mio codice? Grazie! –
Prima di tutto, dai un'occhiata a [writing views in django] (https://docs.djangoproject.com/en/dev/topics/http/views/). Secondo te, devi restituire qualcosa come 'return render_to_response ('my_template.html', my_data_dictionary, context_instance = RequestContext (richiesta)) ' – smang