Order the :class:`~mongoengine.queryset.QuerySet` by the given keys. The order may be specified by prepending each of the keys by a "+" or a "-". Ascending order is assumed if there's no prefix. If no keys are passed, existing ordering is cleared instead. :param ke
(self, *keys, __raw__=None)
| 1142 | return queryset |
| 1143 | |
| 1144 | def order_by(self, *keys, __raw__=None): |
| 1145 | """Order the :class:`~mongoengine.queryset.QuerySet` by the given keys. |
| 1146 | |
| 1147 | The order may be specified by prepending each of the keys by a "+" or |
| 1148 | a "-". Ascending order is assumed if there's no prefix. |
| 1149 | |
| 1150 | If no keys are passed, existing ordering is cleared instead. |
| 1151 | |
| 1152 | :param keys: fields to order the query results by; keys may be |
| 1153 | prefixed with "+" or a "-" to determine the ordering direction. |
| 1154 | :param __raw__: a raw pymongo "sort" argument (provided as a list of (key, direction)) |
| 1155 | see 'key_or_list' in `pymongo.cursor.Cursor.sort doc <https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor.sort>`. |
| 1156 | If both keys and __raw__ are provided, an exception is raised |
| 1157 | """ |
| 1158 | if __raw__ and keys: |
| 1159 | raise OperationError("Can not use both keys and __raw__ with order_by() ") |
| 1160 | |
| 1161 | queryset = self.clone() |
| 1162 | old_ordering = queryset._ordering |
| 1163 | if __raw__: |
| 1164 | new_ordering = __raw__ |
| 1165 | else: |
| 1166 | new_ordering = queryset._get_order_by(keys) |
| 1167 | |
| 1168 | if queryset._cursor_obj: |
| 1169 | # If a cursor object has already been created, apply the sort to it |
| 1170 | if new_ordering: |
| 1171 | queryset._cursor_obj.sort(new_ordering) |
| 1172 | |
| 1173 | # If we're trying to clear a previous explicit ordering, we need |
| 1174 | # to clear the cursor entirely (because PyMongo doesn't allow |
| 1175 | # clearing an existing sort on a cursor). |
| 1176 | elif old_ordering: |
| 1177 | queryset._cursor_obj = None |
| 1178 | |
| 1179 | queryset._ordering = new_ordering |
| 1180 | |
| 1181 | return queryset |
| 1182 | |
| 1183 | def clear_cls_query(self): |
| 1184 | """Clear the default "_cls" query. |