MyModel:
name = models.CharField(max_length=255)
I try to sort the queryset. I just think about this:
obj = MyModel.objects.all().sort_by(-len(name)) #???
Any idea?
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Django has order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field. In the Django model, there is one autogenerated 'id' field. You can use any of the fields (id name, mobile or name) to sort the queryset.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
The new hotness (as of Django 1.8 or so) is Length()
from django.db.models.functions import Length
obj = MyModel.objects.all().order_by(Length('name').asc())
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