12

I'm trying to find a way to take an annotation over two fields on a model added together. Something like:

total_done = qs.values(
    'ability__ability_name',
).extra(
    select={
        'total_amount': 'effective_value + overage',
    }
).annotate(
    total=Sum('total_amount'),
).values(
    'ability__ability_name', 'total_amount'
).order_by('-total_amount')

The above doesn't work and yields the error "Cannot resolve keyword 'total_amount' into field" I already tried the solution indicated here: Using .aggregate() on a value introduced using .extra(select={...}) in a Django Query? However no luck still get the "Cannot resolve keyword 'total_amount' into field"

Anything other than performing the query in raw sql as the querystring that's being passed in could have various filters and excludes already performed on it making that prospect a little complicated. I'm also trying to avoid adding the field to the actual model and calculating it's value during save unless that's the only way.

Community
  • 1
  • 1
John
  • 121
  • 1
  • 3
  • `'total_heal'` is not mentioned in your query, hope you mean `total_amount`? – Torsten Engelbrecht May 17 '11 at 09:50
  • I've been having the same problem recently. From the previous questions it seems that this used to work before -- is it possible (by design or by accident) that it was removed in the later versions?? The problem is apparently not in the SQL clause, but in the aggregate() function, as it works nicely if I call the queryset.total_amount property directly. – Berislav Lopac Mar 23 '12 at 13:16

3 Answers3

2

I think its better to user annotation to get the total_amount value:

total_done = qs.values(
'ability__ability_name',
).annotate(
    total_amount=F('effective_value') + F('overage')
    total=Sum('total_amount'),
).values(
    'ability__ability_name', 'total_amount'
).order_by('-total_amount')
1

Try something like this:

total_done = qs.extra(select = {'total_amount': 'SUM(one_column + another_column)'}, )
Anthony
  • 11,352
  • 9
  • 65
  • 100
yedpodtrzitko
  • 7,507
  • 2
  • 34
  • 38
0

According to the answer to https://stackoverflow.com/a/4348728/122033 (actually in the comments): "Django of course passes the fullName as an alias, which does not work with MySQL" -- and my guess is neither with SQLite, which I've been using. :(

Community
  • 1
  • 1
Berislav Lopac
  • 14,056
  • 6
  • 62
  • 75