Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing extra() on ValuesQuerySet in Django
    primarykey
    data
    text
    <p>I'm trying to calculate a percentage with two values which are themselves aggregated. The SQL query that explains what I'm after is as follows:</p> <pre><code>SELECT (SUM(field_a) / SUM(field_b) * 100) AS percent FROM myapp_mymodel GROUP BY id ORDER BY id </code></pre> <p>I tried to use the following to construct a QuerySet, but unfortunately it doesn't contain the extra field:</p> <pre><code>MyModel.objects.values('id').annotate( sum_field_a=Sum('field_a'), sum_field_b=Sum('field_b')).extra( select={'percent': 'sum_field_a / sum_field_b * 100'}) </code></pre> <p>What irritates me is that - according to the Django documentation - this seems to be the way to go:</p> <blockquote> <p>When a values() clause is used to constrain the columns that are returned in the result set […] instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the values() clause. An annotation is then provided for each unique group; the annotation is computed over all members of the group.</p> <p><em>Source:</em> <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values">http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values</a></p> <p>If you use a values() clause after an extra() clause, any fields defined by a select argument in the extra() must be explicitly included in the values() clause. However, if the extra() clause is used after the values(), the fields added by the select will be included automatically.</p> <p><em>Source:</em> <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#values">http://docs.djangoproject.com/en/dev/ref/models/querysets/#values</a></p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload