0

I have a table with columns, a, b, c, d, e.

Each column is given a random numerical value.

I can then order by that numerical value.

query_results = UserProfile.objects.all().order_by('a')

What i want is the ability to order by the sum of 2 or 3 or even 5 columns. But i cant figure out how to do it lightly.

My answer so far has been some what convoluted. I add an extra column x.

cursor.execute("UPDATE mysite_userprofile SET x = a+b;")

I then order by x. I have to update the column x each time i want different columns added together.

This is not the way to do it i know. i know order_by('a+b') doesn't work but is their another solution just as simple. I looked on django's site but couldn't find anything

JT.
  • 351
  • 1
  • 5
  • 13

2 Answers2

2

The best way is to use extra

UserProfile.objects.extra(
    select={'sum_of_fields': 'a + b + c + d + e'},
    order_by=('sum_of_fields',)
)
Tiago Brandes
  • 274
  • 2
  • 3
0

I think you can order the result in the SQL query. Before you run the SQL query, when you select the columns, you can build the query string in the background.

Coder
  • 886
  • 1
  • 12
  • 28
  • I don't suppose you could give an example. Sorry, im new and ignorant – JT. Nov 29 '11 at 13:43
  • for ex: querystr="SELECT a,b,c,d,e from table order by"; and if you are using checkboxes to select the columns to order by you cand add each time the column name like querystr+=" a".... – Coder Nov 29 '11 at 13:49