|
| 1 | +from itertools import chain |
| 2 | + |
| 3 | +from django.core.exceptions import FieldDoesNotExist |
| 4 | +from django.db import connections |
| 5 | +from django.db.models import QuerySet |
| 6 | +from django.db.models.query import RawModelIterable as BaseRawModelIterable |
| 7 | +from django.db.models.query import RawQuerySet as BaseRawQuerySet |
| 8 | +from django.db.models.sql.query import RawQuery as BaseRawQuery |
| 9 | + |
| 10 | + |
| 11 | +class MongoQuerySet(QuerySet): |
| 12 | + def raw_aggregate(self, pipeline, using=None): |
| 13 | + return RawQuerySet(pipeline, model=self.model, using=using) |
| 14 | + |
| 15 | + |
| 16 | +class RawQuerySet(BaseRawQuerySet): |
| 17 | + def __init__(self, pipeline, model=None, using=None): |
| 18 | + super().__init__(pipeline, model=model, using=using) |
| 19 | + self.query = RawQuery(pipeline, using=self.db, model=self.model) |
| 20 | + # Override the superclass's columns property which relies on PEP 249's |
| 21 | + # cursor.description. Instead, RawModelIterable will set the columns |
| 22 | + # based on the keys in the first result. |
| 23 | + self.columns = None |
| 24 | + |
| 25 | + def iterator(self): |
| 26 | + yield from RawModelIterable(self) |
| 27 | + |
| 28 | + |
| 29 | +class RawQuery(BaseRawQuery): |
| 30 | + def __init__(self, pipeline, using, model): |
| 31 | + self.pipeline = pipeline |
| 32 | + super().__init__(sql=None, using=using) |
| 33 | + self.model = model |
| 34 | + |
| 35 | + def _execute_query(self): |
| 36 | + connection = connections[self.using] |
| 37 | + collection = connection.get_collection(self.model._meta.db_table) |
| 38 | + self.cursor = collection.aggregate(self.pipeline) |
| 39 | + |
| 40 | + def __str__(self): |
| 41 | + return str(self.pipeline) |
| 42 | + |
| 43 | + |
| 44 | +class RawModelIterable(BaseRawModelIterable): |
| 45 | + def __iter__(self): |
| 46 | + """ |
| 47 | + This is copied from the superclass except for the part that sets |
| 48 | + self.queryset.columns from the first result. |
| 49 | + """ |
| 50 | + db = self.queryset.db |
| 51 | + query = self.queryset.query |
| 52 | + connection = connections[db] |
| 53 | + compiler = connection.ops.compiler("SQLCompiler")(query, connection, db) |
| 54 | + query_iterator = iter(query) |
| 55 | + try: |
| 56 | + # Get the columns from the first result. |
| 57 | + try: |
| 58 | + first_result = next(query_iterator) |
| 59 | + except StopIteration: |
| 60 | + # No results. |
| 61 | + return |
| 62 | + self.queryset.columns = list(first_result.keys()) |
| 63 | + # Reset the iterator to include the first item. |
| 64 | + query_iterator = self._make_result(chain([first_result], query_iterator)) |
| 65 | + ( |
| 66 | + model_init_names, |
| 67 | + model_init_pos, |
| 68 | + annotation_fields, |
| 69 | + ) = self.queryset.resolve_model_init_order() |
| 70 | + model_cls = self.queryset.model |
| 71 | + if model_cls._meta.pk.attname not in model_init_names: |
| 72 | + raise FieldDoesNotExist("Raw query must include the primary key") |
| 73 | + fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns] |
| 74 | + converters = compiler.get_converters( |
| 75 | + [f.get_col(f.model._meta.db_table) if f else None for f in fields] |
| 76 | + ) |
| 77 | + if converters: |
| 78 | + query_iterator = compiler.apply_converters(query_iterator, converters) |
| 79 | + for values in query_iterator: |
| 80 | + # Associate fields to values |
| 81 | + model_init_values = [values[pos] for pos in model_init_pos] |
| 82 | + instance = model_cls.from_db(db, model_init_names, model_init_values) |
| 83 | + if annotation_fields: |
| 84 | + for column, pos in annotation_fields: |
| 85 | + setattr(instance, column, values[pos]) |
| 86 | + yield instance |
| 87 | + finally: |
| 88 | + query.cursor.close() |
| 89 | + |
| 90 | + def _make_result(self, query): |
| 91 | + """ |
| 92 | + Convert documents (dictionaries) to tuples as expected by the rest |
| 93 | + of __iter__(). |
| 94 | + """ |
| 95 | + for result in query: |
| 96 | + yield tuple(result.values()) |
0 commit comments