I do this:

for i in Category.query.order_by(desc(Category.position)): print(i.name) 

I receive:

 >>> Category3 >>> Category2 >>> Category1 

If I do this:

 zxc = {c.name: c.position for c in Category.query.order_by(desc(Category.position))} print(zxc) 

I get:

 >>> {'Category1': 1, 'Category2': 2', 'Category3': 3} 

What can be wrong?

  • Vocabulary is by definition unordered, use OrderedDict or something else - andreymal
  • I agree. from collections import OrderedDict - Pavel Durmanov

1 answer 1

In the loop, you output everything one by one. In Example 2, you make a dictionary of values, and only then output it. In general, use:

 ORDER BY Category DESC 

Sort by dropdown.

  • Then you need to create a dictionary based on the desired sequence? - Narnik Gamarnik
  • I understand you need to sort by the fall? - Pavel Durmanov
  • Sorting is normal, the query in the database is ok. The problem is that the dictionary itself stores the data out of order. OrderedDict sorts by key or value, however, I neither in keys, nor in values, store an element by which it is necessary to sort. Ideally, make the dictionary store the sequence initially. - Narnik Gamarnik
  • @NarnikGamarnik: OrderedDict() NOT sorted by key or value. It stores in the order of the bet (specific keys and values ​​do not matter). - jfs