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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With