The following model is available:

class Departments(Document): _id = fields.ObjectIdField() name = fields.StringField(blank=True, null=True) department_id = fields.StringField(blank=True, null=True) # Added list_of_users = fields.ListField(blank=True, null=True) list_of_workstations = fields.ListField(blank=True, null=True) 

As you can see, list_of_users and list_of_workstations are lists of objects.

I wrote a code on Python that pulls all the data out of the database, puts it into the dictionary, and performs sorting, but this method works too slowly.

How can I sort the Департаменты directly into the database by the number of list_of_users or list_of_workstations or by the ratio of list_of_users/list_of_workstations , something like:

 departments = DepartmentStats.objects.order_by(len(list_of_users)).dsc 

or

 departments = DepartmentStats.objects.order_by(len(list_of_users)/len(list_of_workstations)).dsc 

?

  • Obviously not exactly what you need, but you can add a field like number_of_users and write the number there, and sort by this field. - jumpman24

1 answer 1

The fastest option (with requests directly to the database), because the Python data requests in my case (where there is more data than is shown below) processes up to 4 minutes, against a couple of seconds with requests to the database:

 departments = DepartmentStats._get_collection().aggregate([ {"$project": { "department_id": 1, "name": 1, "list_of_users": 1, }}, {"$sort": {"list_of_users": -1}}, ]) 

And in the case when you need to sort by the ratio list_of_users/list_of_workstations

 departments = DepartmentStats._get_collection().aggregate([ {"$project": { "department_id": 1, "name": 1, "list_of_users": 1, "len_list_of_items": {"$divide": [{"$size": "$list_of_users"}, {"$size": "$list_of_workstations"}]} }}, {"$sort": {"len_list_of_items": -1}}, ])