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

爱⌒轻易说出口 提交于 2019-12-18 05:41:29

问题


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?


回答1:


you might have to sort that in python..

sorted(MyModel.objects.all(),key=lambda o:len(o.name),reverse=True)

or I lied ( A quick google search found the following)

MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')



回答2:


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())



回答3:


You can of course sort the results using Python's sorted, but that's not ideal. Instead, you could try this:

MyModel.objects.extra(select={'length':'Length(name)'}).order_by('length')



回答4:


You'll need to use the extra argument to pass an SQL function:

obj = MyModel.objects.all().extra(order_by=['LENGTH(`name`)']) 

Note that this is db-specific: MySQL uses LENGTH, others might use LEN.



来源:https://stackoverflow.com/questions/12804801/django-how-to-sort-queryset-by-number-of-character-in-a-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!