Sort django queryset using a Python list
<p>I have a</p>

<pre><code>Model Car(self.Models)
# a bunch of features here
</code></pre>

<p>then in my views.py, I get all the cars and compute a score for them:</p>

<pre><code>allCars = Car.object.all() # so you get [A, B, C, D]
scoreList = someComputation(allCars) # returns [3,1,2,4]
</code></pre>

<p>then in my template I iterate through allCars to display them; using the ordering the query returned with I get primary key ordering, so</p>

<ol>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ol>

<p>However I would like to know if there is a way to order the queryset using the list I computed in the view, which would yield</p>

<ol>
<li>B</li>
<li>C</li>
<li>A</li>
<li>D</li>
</ol>

<p>so doing something like</p>

<pre><code>allCars.order_by(scoreList)
</code></pre>

<p>First off, to answer your question, you can't use ORM/sql to sort something that's derived from the records with complex logic, unless it's just pure math, which database can do to some extent. </p>

<p>Your next option is to use python built in sorting. However, you can't sort items by a function that "take all in" and "spit all out", meaning your current function is taking a whole list and computed scores and return all scores, because you lost track of what score corresponds to which car.</p>

<p>I would use a function on the model to compute the score, then sort the records accordingly:</p>

<pre><code>class Car(models.Model):
    @property
    def compute_score(self):
      return a_score_based_on_current_car

cars = Car.objects.all()
cars = sorted(cars, key=lambda car: car.compute_score)
</code></pre>

python sql django