Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to sort queryset by number of character in a field

Tags:

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?

like image 674
ben Avatar asked Oct 09 '12 16:10

ben


People also ask

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How do I sort objects in Django?

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.

What does QuerySet []> mean?

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.


Video Answer


1 Answers

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())
like image 172
Dirk Bergstrom Avatar answered Sep 20 '22 19:09

Dirk Bergstrom