There is a selection of objects. Each object has a field "title", which must be sorted. For clarity, below will depict a list of these titles

['30', '10', 'zxc', '7', 'abc', '4', '1', 'абв', 'раа'] 

In a meta model, view, or template, I can apply sorting by the title field. for example

  {% for obj in queryset|dictsort:'title' %} {{ obj.title }} {% endfor %}</ul> 

As a result, we get this sorting

 ['1', '10', '30', '4', '7', 'abc', 'zxc', 'абв', 'раа'] 

In alphabetical order everything is OK, in figures it is necessary ascending, the result is necessary such

 ['1', '4', '7', '10', '30', 'abc', 'zxc', 'абв', 'раа'] 

How is it possible to get?

The methods I saw are based on the extra method and use numeric fields, not strings, for example, if someone tells you how to adapt, it will be great

Can it somehow be possible to set a sorting template in a meta model or view where you can directly specify a list of characters?

 ***UPDATE*** 

Here, the answer brought the solution, however, the sorting does not change, probably incorrectly built a SQL query to the database

 queryset=Test.objects.extra(select={'field': 'SELECT title FROM core_page ORDER BY title ASC limit 1'}) 

    1 answer 1

    Python 2 solution
    In python 3, when you try to compare a string and a number, there will be an exception.
    To sort all objects by the title field, with your condition, you can use the sorted function by writing a handler for the key parameter:

     def key_sort(arg): title = arg.title if title.isdigit(): res = int(title) else: res = title return res 

    Sort queriset:

     new_qs = sorted(YourQueryset, key=key_sort) 

    Or you can use the lambda expression

     new_qs = sorted( YourQueryset, key=lambda x: int(x) if x.title.isdigit() else x.title) 
    • 'QuerySet' object has no attribute 'sort' - while1pass
    • @ while1pass yes, I forgot to add that you need to get all the title fields first. Queriset has no such method, for queriset use the sorted function - Ivan Semochkin
    • I do not understand your thoughts - while1pass
    • @ while1pass updated the answer, look. Or do you need to display the entire object sorted by this field? - Ivan Semochkin
    • one
      This solution involves comparing the number with the string, in the second python the numbers are always considered to be smaller than the rows, and in the third it was cut - andreymal