Custom ordering in Django

后端 未结 4 777
梦毁少年i
梦毁少年i 2020-11-29 01:55

How do you define a specific ordering in Django QuerySets?

Specifically, if I have a QuerySet like so: [\'a10\', \'a1\', \'a2\']

4条回答
  •  不知归路
    2020-11-29 02:07

    @Jarret's answer (do the sort in Python) works great for simple cases. As soon as you have a large table and want to, say, pull only the first page of results sorted in a certain way, this approach breaks (you have to pull every single row from the database before you can do the sort). At that point I would look into adding a denormalized "sort" field which you populate from the "name" field at save-time, that you can sort on at the DB-level in the usual way.

提交回复
热议问题