Reputation: 526
I want to order result of a query (done by .filter) based on a list of values I provide.
I have a importance column in my database and the values are none, not important, important, very important. But when I make a query, Django returns whichever row is the first. I want to specify to put "very important" first, "important" second, "not important" third and the last would be none.
1, word, not important
2, word2, none
3, word3, very important
4, word4, important
3, word3, very important
4, word4, important
1, word, not important
2, word2, none
How can I make this order?
Upvotes: 0
Views: 125
Reputation: 36
You can use the Django model field's choices options and map the values to an integer, based on the importance. Then it will be easier to sort and also it will boost performance up to some extent. Refer the official documentation for more information regarding implementation.
Your model may look something like the below example:
class YourModel(models.Model):
IMPORTANCE_CHOICES = [
(1, 'VeryImportant'),
(2, 'Important'),
(3, 'NotImportant'),
]
your_field_name = models.IntegerField(
choices=IMPORTANCE_CHOICES,
default=0,
)
Please change the field definition as per your requirement.
Upvotes: 1