7👍
✅
It’s not possible set the default order to case-insensitive in the model meta options (source).
What you can do is use the order_by method of the QuerySet
of your model:
from django.db.models.functions import Lower
Ingredient.objects.order_by(Lower('name'))
As stated already in this answer
To be able to have it as a default ordering (and avoid repeating the order_by
method on each one of your querysets), you might want to create a custom Manager
class for your Ingredient
model:
# managers.py
from django.db.models.functions import Lower
class OrderedIngredientManager(models.Manager):
def get_queryset(self):
return super().get_queryset().order_by(Lower('name'))
# models.py
from .managers import OrderedIngredientManager
class Ingredient(models.Model):
name = models.CharField(max_length=200,unique=True,null=False)
slug = models.SlugField(unique=True)
ordered_objects = OrderedIngredientManager()
So you can have all your QuerySet
ordered:
Ingredient.ordered_objects.all()
12👍
I tested with django 2.0.7 and using Upper works :
from django.db.models.functions import Upper
class Ingredient(models.Model):
class Meta:
ordering = [Upper('name'), ]
name = models.CharField(max_length=200,unique=True,null=False)
- [Django]-Crontab is running but still not executing command Django
- [Django]-Unknown command: 'collectstatic' Django 1.7
- [Django]-Django .."join" query?
1👍
You can use it by using F from django models
from django.db.models import F
class Ingredient(models.Model):
class Meta:
ordering = [F('name').asc(nulls_last=True)]
- [Django]-In Django, how to rename user model?
- [Django]-Django filters, got an unexpected keyword argument
- [Django]-Django Humanize naturaltime templatetag only partly translating
Source:stackexchange.com