lundi 8 juin 2015

How to sort multiple columns using SQLAlchemy?

So I have a parameter called 'sort_param' that contains list of the sorting parameter for example

sort_param[0] :
field : 'name'
dir : 'asc'


sort_param[1] :
field : 'id'
dir : 'desc'

then for example I have this list :

id  |  name
1   |  anna
2   |  inna
3   |  anna

using those parameters above, the result should be :

id  |  name
3   |  anna
1   |  anna
2   |  inna

I have tried to do it using this loop :

      if query_sort is None:
          select_query =\
          select_query\
          .order_by(asc('employee_id'))

          return select_query

      for s in query_sort:
          if s.dir == 'asc':
              select_query =\
              select_query\
              .order_by(asc(getattr(Employee, s.field)))
          else:
              select_query =\
              select_query\
              .order_by(desc(getattr(Employee, s.field)))

      return select_query

but it didn't work, instead of sorting with two parameters, it actually only sorting with one parameter (always the last one). I'm still confused on how to do it the right way. Any help would be appreciated. Thanks in advance

Aucun commentaire:

Enregistrer un commentaire