migreva
migreva

Reputation: 876

Count Multiple Columns in Django and Order

We have a table in our database called Analysis, each object of which stores build-specific information. Unfortunately, due to the limitations of how the DB was originally set up, we have this information stored in two columns: build_info and build. Analysis objects will only have one of these fields valid, the other will be NULL (so you can't have build_info and build be some value for the same object).

What I want to do is get the highest count of build-specific columns in this table. The SQL query is pretty straightforward. The Django ORM query (of course) is slightly more complicated. Here's the exact SQL query I want (this returns exactly the information I need):

select build_info, build_id, count(*) as build_count
from analysis
group by build_info, build_id
order by build_count desc

Pretty simple. Here's what I have so far for the Django query (note that this query doesn't yet work:

Analysis.objects.values("build_info", "build").annotate(build_info_count = Count("build_info"), build_count = Count("build")).order_by([?!?!?])

The hang up occurs in the order_by() call. Currently, the QuerySet that is returned has two different columns for count: build_info_count and build_count. What I need to do is order the returned QuerySet by the combination of build_info_count and build_count, but the order_by() function only takes one argument, and I can't yet find a way to combine multiple Count() objects.

Is there a way to count multiple columns in Django? Or at least combine the counts of individual columns into one? Or is there some other way I can accomplish the above SQL query?

Upvotes: 1

Views: 1084

Answers (1)

migreva
migreva

Reputation: 876

I ended up doing a raw query. The Django ORM is great for a lot of stuff, but anything overly complicated is better off in a raw SQL query (performance is better too).

Upvotes: 1

Related Questions