Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Add field to queryset to store computation results

Tags:

People also ask

Can you filter a QuerySet?

Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.

What is annotate in Django QuerySet?

annotate()Annotates each object in the QuerySet with the provided list of query expressions.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


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.

Here's my code:

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)

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

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.

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

Thanks!

EDIT:

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

Thanks!