12

I have the following Django Model:

class myModel(models.Model):
    name = models.CharField(max_length=255, unique=True)
    score = models.FloatField()

There are thousands of values in the DB for this model. I would like to efficiently and elegantly use that QuerySets alone to get the top-ten highest scores and display the names with their scores in descending order of score. So far it is relatively easy.

Here is where the wrinkle is: If there are multiple myModels who are tied for tenth place, I want to show them all. I don't want to only see some of them. That would unduly give some names an arbitrary advantage over others. If absolutely necessary, I can do some post-DB list processing outside of Querysets. However, the main problem I see is that there is no way I can know apriori to limit my DB query to the top 10 elements since for all I know there may be a million records all tied for tenth place.

Do I need to get all the myModels sorted by score and then do one pass over them to calculate the score-threshold? And then use that calculated score-threshold as a filter in another Queryset?

If I wanted to write this in straight-SQL could I even do it in a single query?

3 Answers 3

19
+50

Of course you can do it in one SQL query. Generating this query using django ORM is also easily achievable.

top_scores = (myModel.objects
                     .order_by('-score')
                     .values_list('score', flat=True)
                     .distinct())
top_records = (myModel.objects
                      .order_by('-score')
                      .filter(score__in=top_scores[:10]))

This should generate single SQL query (with subquery).

5
  • 4
    Not only is this a good answer, but I also love the use of braces to avoid using `\` at the end of lines.
    – elssar
    Jan 28, 2014 at 12:56
  • This will get all objects with a score that match any of the top 10 scores, not the top 10 elements + any extras (because of .distinct()). So if you have 10 elements with a score of 100, 10 with 99 etc, you will end up with 100 results instead of the desired 10. Michal's answer doesn't have this issue.
    – dwurf
    Jan 29, 2014 at 5:11
  • @dwurf I think the question was exactly how to get 100 results in the example you've provided. BTW Michal's answer behaves the same way as mine. Jan 31, 2014 at 13:25
  • @KrzysztofSzularz nonsense. Saqib explicitly states that he wants to include all elements that tie for last place. Michal's code will do this. Your code will include all elements that tie for any of the ten highest scores (yes, I've tested it). Simply remove the .distinct() and your code behaves correctly, although you might want to add Michal's excellent advice about index creation.
    – dwurf
    Feb 3, 2014 at 5:24
  • @dwurf if my understanding of Saqib question is correct, he wants all ties in top positions. Feb 4, 2014 at 10:14
2

As an alternative, you can also do it with two SQL queries, what might be faster with some databases than the single SQL query approach (IN operation is usually more expensive than comparing):

myModel.objects.filter(
    score__gte=myModel.objects.order_by('-score')[9].score
)

Also while doing this, you should really have an index on score field (especially when talking about millions of records):

class myModel(models.Model):
    name = models.CharField(max_length=255, unique=True)
    score = models.FloatField(db_index=True)
2
  • Won't this simply choose the 9th element of myModel.objects.order_by('-score')? You probably meant to do myModel.objects.order_by('-score')[:9]
    – Blairg23
    May 4, 2018 at 7:43
  • It chooses 9th score and then filters all models with higher score. Your approach should work as well... May 5, 2018 at 9:20
0

As an alternative to @KrzysztofSzularz's answer, you can use raw sql to do this too.

There are 2 SQL operations to get what you want

SELECT score from my_application_mymodel order by score desc limit 10;

Above sql will return top 10 scores (limit does this)

SELECT name, score from my_application_mymodel where score in (***) order by score desc;

That will return you all the results whom score value is within the first query result.

SELECT name, score from my_application_mymodel where score in (SELECT score from my_application_mymodel order by score desc limit 10) order by score desc;

You can use Raw Queries, but probably you will got error messages while you try to run this. So using custom queries is the best

from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT name, score from my_application_mymodel where score in (SELECT score from my_application_mymodel order by score desc limit 10) order by score desc;")
return cursor.fetchall()

That will return you a list:

[("somename", 100.9),
 ("someothername", 99.9)
...
]

Django names tables according to your django model name (all lowercase) and application name in which your model lives under and join these to with an underscore. Like my_application_mymodel

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.