Soy bastante nuevo en Django y vengo del mundo de PHP. Estoy tratando de 'agregar' un campo a un conjunto de consulta después de calcular cosas, y no sé cómo hacerlo. En PHP, simplemente agregaría una columna en una matriz y almacenaría mis cosas en ella.Django - Agregar campo a queryset para almacenar los resultados de cálculo
Aquí está mi código:
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)
Así que, básicamente, en mi plantilla que me gustaría ser capaz de llamar: { % para nuevoElemento en newthings_list%} {{ newthing.to_add}} {% end%}
TL; DR: Básicamente quiero recuperar una lista de cosas de mi base de datos, y en esta lista de objetos AGREGAR un campo que contendrá un valor calculado.
Avísame si no está claro, estoy teniendo dificultades para cambiar de php a django jaja.
Gracias!
EDIT:
Por lo tanto, estoy tratando con un dictionnary, pero debo estar perdiendo la lógica:
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
Y luego, cuando voy a conseguir que el trabajo, no sé cómo acceder a él en la plantilla:
{% for id in my_list %}
{{newthing[id]}} ? Or something like newthing.id ?
{% end %}
¡Gracias!
¡Hola y gracias! Intenté con dictionnaries, esa es la parte posterior a la "edición" de mi pregunta, pero todavía no tengo suerte. ¿Qué he hecho mal en mi código? ¡Gracias! –
Antes que nada, mira [escribiendo visitas en django] (https://docs.djangoproject.com/en/dev/topics/http/views/). En su opinión, debe devolver algo como 'return render_to_response ('my_template.html', my_data_dictionary, context_instance = RequestContext (request)) ' – smang