|
| 1 | +from django.db.models import QuerySet |
| 2 | +from django.http import HttpRequest |
| 3 | +from rest_framework import filters, viewsets |
| 4 | + |
| 5 | + |
| 6 | +class QfcOrderingFilter(filters.OrderingFilter): |
| 7 | + """Custom QFC OrderingFilter class that allows usage of custom attributes expression. |
| 8 | +
|
| 9 | + Use it in a ModelViewSet by setting the `filter_backends` and `ordering_fields` fields. |
| 10 | + It is possible to use an `ordering_fields` expression value with attributes. |
| 11 | + Custom attributes expression has form : "my_field::alias=my_field_alias,key=value" |
| 12 | + """ |
| 13 | + |
| 14 | + SEPARATOR = "::" |
| 15 | + TOKENS_LIST_SEPARATOR = "," |
| 16 | + TOKENS_VALUE_SEPARATOR = "=" |
| 17 | + |
| 18 | + def _get_query_field(self, fields: list[str], term: str) -> str | None: |
| 19 | + """Searches a term in a query field list. |
| 20 | +
|
| 21 | + The field list elements may start with "-". |
| 22 | + This method should be used to search a term from a query's ordering fields. |
| 23 | +
|
| 24 | + Args: |
| 25 | + fields (list[str]): list of fields to search |
| 26 | + term (str): term to search in the list |
| 27 | + Returns: |
| 28 | + str | None: the matching field, if present in the list |
| 29 | + """ |
| 30 | + for field in fields: |
| 31 | + compare_value = field |
| 32 | + |
| 33 | + # the "-" is used when the fields are sorted descending |
| 34 | + if field.startswith("-"): |
| 35 | + compare_value = field[1:] |
| 36 | + |
| 37 | + if compare_value != term: |
| 38 | + continue |
| 39 | + |
| 40 | + return field |
| 41 | + return None |
| 42 | + |
| 43 | + def _parse_tokenized_attributes(self, raw: str) -> dict[str, str]: |
| 44 | + """Parses an ordering field attributes expression. |
| 45 | +
|
| 46 | + Args: |
| 47 | + raw (str): raw expression to parse, e.g.: "alias=my_field_alias,key=value" |
| 48 | + Returns: |
| 49 | + dict[str, str]: dict containing the expression's attributes |
| 50 | + """ |
| 51 | + definition_attrs = raw.split(self.TOKENS_LIST_SEPARATOR) |
| 52 | + |
| 53 | + attr_dict = {} |
| 54 | + for attr in definition_attrs: |
| 55 | + token, value = attr.split(self.TOKENS_VALUE_SEPARATOR, 1) |
| 56 | + attr_dict[token] = value |
| 57 | + |
| 58 | + return attr_dict |
| 59 | + |
| 60 | + def _parse_definition(self, definition: str) -> tuple[str, dict[str, str]]: |
| 61 | + """Parses a custom ordering field with attributes expression. |
| 62 | +
|
| 63 | + Args: |
| 64 | + definition (str): raw definition of the ordering field to parse, |
| 65 | + e.g.: "my_field::alias=my_field_alias,key=value" |
| 66 | + Returns : |
| 67 | + tuple[str, dict[str, str]]: tuple containing the field name (1st) and its attributes dict (2nd) |
| 68 | + """ |
| 69 | + name, attr_str = definition.split(self.SEPARATOR, 1) |
| 70 | + attrs = self._parse_tokenized_attributes(attr_str) |
| 71 | + |
| 72 | + return name, attrs |
| 73 | + |
| 74 | + def remove_invalid_fields( |
| 75 | + self, |
| 76 | + queryset: QuerySet, |
| 77 | + fields: list[str], |
| 78 | + view: viewsets.ModelViewSet, |
| 79 | + request: HttpRequest, |
| 80 | + ) -> list[str]: |
| 81 | + """Process ordering fields by parsing custom field expression. |
| 82 | +
|
| 83 | + Custom attributes expression has form : "my_field::alias=my_field_alias,key=value". |
| 84 | + In the above example, `alias` is the URL GET param value, |
| 85 | + but `my_field` is the real model field. |
| 86 | +
|
| 87 | + Args: |
| 88 | + queryset (QuerySet): Django's ORM queryset of the same model as the one used in view of the `ModelViewSet` |
| 89 | + fields (list[str]): ordering fields passed to the HTTP querystring |
| 90 | + view (ModelViewSet): DRF view instance |
| 91 | + request (HttpRequest): DRF request instance |
| 92 | + Returns : |
| 93 | + list[str]: parsed ordering fields where aliases have been replaced |
| 94 | + """ |
| 95 | + base_fields = super().remove_invalid_fields(queryset, fields, view, request) |
| 96 | + valid_fields = [] |
| 97 | + |
| 98 | + for field_name, _verbose_name in self.get_valid_fields( |
| 99 | + queryset, view, context={"request": request} |
| 100 | + ): |
| 101 | + # standard handling of fields from the base class |
| 102 | + query_field_name = self._get_query_field(base_fields, field_name) |
| 103 | + |
| 104 | + if query_field_name: |
| 105 | + valid_fields.append(query_field_name) |
| 106 | + continue |
| 107 | + |
| 108 | + # skip fields without custom attributes expression |
| 109 | + if self.SEPARATOR not in field_name: |
| 110 | + continue |
| 111 | + |
| 112 | + definition_name, attrs = self._parse_definition(field_name) |
| 113 | + alias = attrs.get("alias", definition_name) |
| 114 | + query_field_name = self._get_query_field(fields, alias) |
| 115 | + |
| 116 | + # field is not in the HTTP GET request querystring |
| 117 | + if not query_field_name: |
| 118 | + continue |
| 119 | + |
| 120 | + if query_field_name.startswith("-"): |
| 121 | + definition_name = f"-{definition_name}" |
| 122 | + |
| 123 | + valid_fields.append(definition_name) |
| 124 | + |
| 125 | + return valid_fields |
0 commit comments