|
| 1 | +from typing import ( |
| 2 | + Any, |
| 3 | + Dict, |
| 4 | + Generator, |
| 5 | + Iterable, |
| 6 | + List, |
| 7 | + Optional, |
| 8 | + Type, |
| 9 | + TypeVar, |
| 10 | + cast, |
| 11 | +) |
| 12 | + |
| 13 | +from django.core.exceptions import FieldDoesNotExist |
| 14 | +from django.db import connection, models |
| 15 | +from django.db.models import Field, Model |
| 16 | +from django.db.models.expressions import Expression |
| 17 | + |
| 18 | +from .fields import inspect_model_local_concrete_fields |
| 19 | + |
| 20 | +TModel = TypeVar("TModel", bound=models.Model) |
| 21 | + |
| 22 | + |
| 23 | +def _construct_model( |
| 24 | + model: Type[TModel], |
| 25 | + columns: Iterable[str], |
| 26 | + values: Iterable[Any], |
| 27 | + *, |
| 28 | + apply_converters: bool = True |
| 29 | +) -> TModel: |
| 30 | + fields_by_name_and_column = {} |
| 31 | + for field in inspect_model_local_concrete_fields(model): |
| 32 | + fields_by_name_and_column[field.attname] = field |
| 33 | + |
| 34 | + if field.db_column: |
| 35 | + fields_by_name_and_column[field.db_column] = field |
| 36 | + |
| 37 | + indexable_columns = list(columns) |
| 38 | + |
| 39 | + row = {} |
| 40 | + |
| 41 | + for index, value in enumerate(values): |
| 42 | + column = indexable_columns[index] |
| 43 | + try: |
| 44 | + field = cast(Field, model._meta.get_field(column)) |
| 45 | + except FieldDoesNotExist: |
| 46 | + field = fields_by_name_and_column[column] |
| 47 | + |
| 48 | + field_column_expression = field.get_col(model._meta.db_table) |
| 49 | + |
| 50 | + if apply_converters: |
| 51 | + converters = cast(Expression, field).get_db_converters( |
| 52 | + connection |
| 53 | + ) + connection.ops.get_db_converters(field_column_expression) |
| 54 | + |
| 55 | + converted_value = value |
| 56 | + for converter in converters: |
| 57 | + converted_value = converter( |
| 58 | + converted_value, |
| 59 | + field_column_expression, |
| 60 | + connection, |
| 61 | + ) |
| 62 | + else: |
| 63 | + converted_value = value |
| 64 | + |
| 65 | + row[field.attname] = converted_value |
| 66 | + |
| 67 | + instance = model(**row) |
| 68 | + instance._state.adding = False |
| 69 | + instance._state.db = connection.alias |
| 70 | + |
| 71 | + return instance |
| 72 | + |
| 73 | + |
| 74 | +def models_from_cursor( |
| 75 | + model: Type[TModel], cursor, *, related_fields: List[str] = [] |
| 76 | +) -> Generator[TModel, None, None]: |
| 77 | + """Fetches all rows from a cursor and converts the values into model |
| 78 | + instances. |
| 79 | +
|
| 80 | + This is roughly what Django does internally when you do queries. This |
| 81 | + goes further than `Model.from_db` as it also applies converters to make |
| 82 | + sure that values are converted into their Python equivalent. |
| 83 | +
|
| 84 | + Use this when you've outgrown the ORM and you are writing performant |
| 85 | + queries yourself and you need to map the results back into ORM objects. |
| 86 | +
|
| 87 | + Arguments: |
| 88 | + model: |
| 89 | + Model to construct. |
| 90 | +
|
| 91 | + cursor: |
| 92 | + Cursor to read the rows from. |
| 93 | +
|
| 94 | + related_fields: |
| 95 | + List of ForeignKey/OneToOneField names that were joined |
| 96 | + into the raw query. Use this to achieve the same thing |
| 97 | + that Django's `.select_related()` does. |
| 98 | +
|
| 99 | + Field names should be specified in the order that they |
| 100 | + are SELECT'd in. |
| 101 | + """ |
| 102 | + |
| 103 | + columns = [col[0] for col in cursor.description] |
| 104 | + field_offset = len(inspect_model_local_concrete_fields(model)) |
| 105 | + |
| 106 | + rows = cursor.fetchmany() |
| 107 | + |
| 108 | + while rows: |
| 109 | + for values in rows: |
| 110 | + instance = _construct_model( |
| 111 | + model, columns[:field_offset], values[:field_offset] |
| 112 | + ) |
| 113 | + |
| 114 | + for index, related_field_name in enumerate(related_fields): |
| 115 | + related_model = model._meta.get_field( |
| 116 | + related_field_name |
| 117 | + ).related_model |
| 118 | + if not related_model: |
| 119 | + continue |
| 120 | + |
| 121 | + related_field_count = len( |
| 122 | + inspect_model_local_concrete_fields(related_model) |
| 123 | + ) |
| 124 | + |
| 125 | + # autopep8: off |
| 126 | + related_columns = columns[ |
| 127 | + field_offset : field_offset + related_field_count # noqa |
| 128 | + ] |
| 129 | + related_values = values[ |
| 130 | + field_offset : field_offset + related_field_count # noqa |
| 131 | + ] |
| 132 | + # autopep8: one |
| 133 | + |
| 134 | + if ( |
| 135 | + not related_columns |
| 136 | + or not related_values |
| 137 | + or all([value is None for value in related_values]) |
| 138 | + ): |
| 139 | + continue |
| 140 | + |
| 141 | + related_instance = _construct_model( |
| 142 | + cast(Type[Model], related_model), |
| 143 | + related_columns, |
| 144 | + related_values, |
| 145 | + ) |
| 146 | + instance._state.fields_cache[related_field_name] = related_instance # type: ignore |
| 147 | + |
| 148 | + field_offset += len( |
| 149 | + inspect_model_local_concrete_fields(related_model) |
| 150 | + ) |
| 151 | + |
| 152 | + yield instance |
| 153 | + |
| 154 | + rows = cursor.fetchmany() |
| 155 | + |
| 156 | + |
| 157 | +def model_from_cursor( |
| 158 | + model: Type[TModel], cursor, *, related_fields: List[str] = [] |
| 159 | +) -> Optional[TModel]: |
| 160 | + return next( |
| 161 | + models_from_cursor(model, cursor, related_fields=related_fields), None |
| 162 | + ) |
| 163 | + |
| 164 | + |
| 165 | +def model_from_dict( |
| 166 | + model: Type[TModel], row: Dict[str, Any], *, apply_converters: bool = True |
| 167 | +) -> TModel: |
| 168 | + return _construct_model( |
| 169 | + model, row.keys(), row.values(), apply_converters=apply_converters |
| 170 | + ) |
0 commit comments