XenoChrist - 5 months ago 47

SQL Question

I have a

`Model Car(self.Models)`

# a bunch of features here

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

`allCars = Car.object.all() # so you get [A, B, C, D]`

scoreList = someComputation(allCars) # returns [3,1,2,4]

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

- A
- B
- C
- D

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

- B
- C
- A
- D

so doing something like

`allCars.order_by(scoreList)`

Answer

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.

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.

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

```
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)
```