Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: "order" a queryset based on a boolean field

Tags:

django

I want to get all Menù instances in this way:

-at the top positions those instances who have my_boolean_field set to True

-at the last positions those instances that have my_boolean_field set to False

Here is my Menù model and my query:

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)

# In my View:
my_query_set = Menù.objects.all().order_by('my_boolean_field')

I've also searched for a group_by option but I didn't find anything in Django ORM

like image 587
Tajinder Singh Avatar asked Mar 26 '19 19:03

Tajinder Singh


People also ask

Does order of filter matter Django?

If you are just doing two simple filter operations, then you're correct that order doesn't matter, but be careful. There are examples of when the order of your queryset methods do matter: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses.

What is Boolean field in Django?

BooleanField is a true/false field. It is like a bool field in C/C+++. The default form widget for this field is CheckboxInput, or NullBooleanSelect if null=True.

Can we order data in descending order in Django?

When we read the data from the model, Django returns queryset. Django has order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field.


1 Answers

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
like image 145
Mojtaba Kamyabi Avatar answered Oct 20 '22 03:10

Mojtaba Kamyabi