stackyname
stackyname

Reputation: 526

How can I order a queryset in Django by custom values?

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.

Curent Query Result

1, word, not important
2, word2, none
3, word3, very important
4, word4, important

Query result I want to achieve

3, word3, very important
4, word4, important
1, word, not important
2, word2, none

How can I make this order?

Upvotes: 0

Views: 125

Answers (1)

Rupesh Gangwani
Rupesh Gangwani

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

Related Questions