Coverage for pyodmongo/models/sort_operators.py: 100%
11 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-16 15:08 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-01-16 15:08 +0000
1from pydantic import BaseModel
2from .db_field_info import DbField
5class SortOperator(BaseModel):
6 """
7 Represents a sort operation in a PyODMongo query, allowing for the specification
8 of sorting criteria on database fields. This model is used to construct the sorting
9 part of a query, defining how the results should be ordered.
11 Attributes:
12 operators (tuple[tuple[DbField, int], ...]): A tuple of tuples, where each
13 inner tuple contains a DbField and an integer indicating the
14 sort order. The integer should be 1 for ascending order and -1
15 for descending order.
17 Methods:
18 to_dict(): Converts the sort operation to a dictionary format suitable for
19 use in a MongoDB query. Validates that the sort order values are
20 either 1 or -1.
21 """
23 operators: tuple[tuple[DbField, int], ...]
25 def to_dict(self):
26 dct = {}
27 for operator in self.operators:
28 if operator[1] not in (1, -1):
29 raise ValueError("Only values 1 ascending and -1 descending are valid")
30 dct[operator[0].path_str] = operator[1]
31 return dct