Transform a query from Django-style format to Mongo format.
(_doc_cls=None, **kwargs)
| 73 | |
| 74 | # TODO make this less complex |
| 75 | def query(_doc_cls=None, **kwargs): |
| 76 | """Transform a query from Django-style format to Mongo format.""" |
| 77 | mongo_query = {} |
| 78 | merge_query = defaultdict(list) |
| 79 | for key, value in sorted(kwargs.items()): |
| 80 | if key == "__raw__": |
| 81 | handle_raw_query(value, mongo_query) |
| 82 | continue |
| 83 | |
| 84 | parts = key.rsplit("__") |
| 85 | indices = [(i, p) for i, p in enumerate(parts) if p.isdigit()] |
| 86 | parts = [part for part in parts if not part.isdigit()] |
| 87 | # Check for an operator and transform to mongo-style if there is |
| 88 | op = None |
| 89 | if len(parts) > 1 and parts[-1] in MATCH_OPERATORS: |
| 90 | op = parts.pop() |
| 91 | |
| 92 | # Allow to escape operator-like field name by __ |
| 93 | if len(parts) > 1 and parts[-1] == "": |
| 94 | parts.pop() |
| 95 | |
| 96 | negate = False |
| 97 | if len(parts) > 1 and parts[-1] == "not": |
| 98 | parts.pop() |
| 99 | negate = True |
| 100 | |
| 101 | if _doc_cls: |
| 102 | # Switch field names to proper names [set in Field(name='foo')] |
| 103 | try: |
| 104 | fields = _doc_cls._lookup_field(parts) |
| 105 | except Exception as e: |
| 106 | raise InvalidQueryError(e) |
| 107 | parts = [] |
| 108 | |
| 109 | CachedReferenceField = _import_class("CachedReferenceField") |
| 110 | GenericReferenceField = _import_class("GenericReferenceField") |
| 111 | |
| 112 | cleaned_fields = [] |
| 113 | for field in fields: |
| 114 | append_field = True |
| 115 | if isinstance(field, str): |
| 116 | parts.append(field) |
| 117 | append_field = False |
| 118 | # is last and CachedReferenceField |
| 119 | elif isinstance(field, CachedReferenceField) and fields[-1] == field: |
| 120 | parts.append("%s._id" % field.db_field) |
| 121 | else: |
| 122 | parts.append(field.db_field) |
| 123 | |
| 124 | if append_field: |
| 125 | cleaned_fields.append(field) |
| 126 | |
| 127 | # Convert value to proper value |
| 128 | field = cleaned_fields[-1] |
| 129 | |
| 130 | singular_ops = [None, "ne", "gt", "gte", "lt", "lte", "not"] |
| 131 | singular_ops += STRING_OPERATORS |
| 132 | if op in singular_ops: |
nothing calls this directly
no test coverage detected