Order search results by column

I’m trying to get the results in descending numeric order.

data = {}
column = query["keywords"]
order = tables.order_by(column, ascending=False)
params = {column: q.greater_than(0)}
for row in app_tables.nutricalc.client_readable(q.only_cols("Food", column)).search(order, **params):
    data[row["Food"]] = row[column]

It would be really helpful if you tell us what exactly is not working with your current code. It seems fine so far.

1 Like

For these columns: food, nutrient1, nutrient2… I want to get the foods with the highest values for a nutrient in descending order.
With the above code the values in the nutrient column are not ordered.

What is the data type of the nutrient column?

Food is text, nutrients are number.

1 Like

Could you give an example of

  1. Your unsorted data (only what’s needed to illustrate the problem)
  2. How your code currently sorts it
  3. How you want it sorted

The issue is with returned data, same as here:

Si you still need an answer, it is the answer on that post good for you?

I tried this client module:

DictHelpers

import anvil.server

try:
  from functools import wraps
except:
  wraps = lambda f: f

@anvil.server.portable_class
class odict(dict):
    def __serialize__(self, global_data):
        return list(self.items())
    def __deserialize__(self, data, global_data):
        self.__init__(data)
  

def convert_to_odict(arg):
  """only worry about nested dicts, lists and tuples"""
  if isinstance(arg, dict):
    od = odict()
    for key, val in arg.items():
      od[key] = convert_to_odict(val)
    return od
  elif isinstance(arg, (list, tuple)):
    l = []
    for val in arg:
      l.append(convert_to_odict(val))
    return l
  else:
    return arg


def preserve_dict_order(f):
  @wraps(f)
  def wrapper(*args, **kwargs):
    return convert_to_odict(f(*args, **kwargs))
  return wrapper

def serialize_args(*args):
  return convert_to_odict(args)

My code:

from .DictHelpers import preserve_dict_order

@preserve_dict_order
def return_ordered(obj):
  return obj

@anvil.server.route("/serverpage")
def servercall():
    query = anvil.server.request.body_json
    data = get_data(query)
    if len(data) > 0:
      #return data
      return_ordered(data)

It returns null.

request.body_json only contains data for well formed requests with Content-Type: application/json. Perhaps your problem is there.

What is get_data?

Are you trying to get a dict with the keys in the same order it was sent through a json request?

If this is the case, then (1) you should have stated this at the beginning and (2) this is a lot to ask. There are many moving parts and (as far as I know) none of them explicitly says in their documentation that a request preserves the order of the keys. A dictionary is converted to json, serialized in a request, sent, received, converted to python, serialized again, sent to the client, deserialized to javascript/python/skulpt…

If this is not the case, then I will repeat what @divyeshlakhotia and @p.colbert already said: please ask the question providing more details about what you do, what you get and what you want to get instead.

See here: How to ask a good question

This always returns None. You call the function return_ordered, but you don’t return its value, e.g. return return_ordered(data).

Not saying that’s going to make anything else work, but that’s definitely an issue.

I’ve decided to use list of dicts instead of a dict, this way the returned data order is preserved.

        #data[row["Food"]] = row[column]
        data.append({row["Food"]: row[column]})