[Fixed]-Django: "order" a queryset based on a boolean field

36👍

you can add - to your order_by query for sort in descending order like this:

my_query_set = Menù.objects.all().order_by('-my_boolean_field')  # first get True ones then get False ones

another way is add ordering to your model Meta class like this:

class Menù(models.Model):
    id_menù = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)
    my_boolean_field = models.BooleanField(default=False)

    class Meta:
        ordering = ('-my_boolean_field ',)

after this change your queries on my_boolean_field will be sorted descend by default and not need to use order_by('-my_boolean_field'):

my_query_set = Menù.objects.all()  # results will be sorted by my_boolean_field in reverse order

Leave a comment