|
3 | 3 | from typing import Dict, Iterable, List, Optional, Tuple, Union
|
4 | 4 |
|
5 | 5 | from django.core.exceptions import SuspiciousOperation
|
6 |
| -from django.db import models, router |
| 6 | +from django.db import connections, models, router |
7 | 7 | from django.db.models import Expression
|
8 | 8 | from django.db.models.fields import NOT_PROVIDED
|
9 | 9 |
|
@@ -389,14 +389,36 @@ def is_empty(r):
|
389 | 389 | )
|
390 | 390 | return self.bulk_insert(rows, return_model, using=using)
|
391 | 391 |
|
392 |
| - def _create_model_instance(self, field_values, using: Optional[str] = None): |
| 392 | + def _create_model_instance( |
| 393 | + self, field_values: dict, using: str, apply_converters: bool = True |
| 394 | + ): |
393 | 395 | """Creates a new instance of the model with the specified field.
|
394 | 396 |
|
395 | 397 | Use this after the row was inserted into the database. The new
|
396 | 398 | instance will marked as "saved".
|
397 | 399 | """
|
398 | 400 |
|
399 |
| - instance = self.model(**field_values) |
| 401 | + converted_field_values = field_values.copy() |
| 402 | + |
| 403 | + if apply_converters: |
| 404 | + connection = connections[using] |
| 405 | + |
| 406 | + for field in self.model._meta.local_concrete_fields: |
| 407 | + if field.attname not in converted_field_values: |
| 408 | + continue |
| 409 | + |
| 410 | + # converters can be defined on the field, or by |
| 411 | + # the database back-end we're using |
| 412 | + converters = field.get_db_converters( |
| 413 | + connection |
| 414 | + ) + connection.ops.get_db_converters(field) |
| 415 | + |
| 416 | + for converter in converters: |
| 417 | + converted_field_values[field.attname] = converter( |
| 418 | + converted_field_values[field.attname], field, connection |
| 419 | + ) |
| 420 | + |
| 421 | + instance = self.model(**converted_field_values) |
400 | 422 | instance._state.db = using
|
401 | 423 | instance._state.adding = False
|
402 | 424 |
|
@@ -444,7 +466,9 @@ def _build_insert_compiler(
|
444 | 466 | ).format(index)
|
445 | 467 | )
|
446 | 468 |
|
447 |
| - objs.append(self._create_model_instance(row, using)) |
| 469 | + objs.append( |
| 470 | + self._create_model_instance(row, using, apply_converters=False) |
| 471 | + ) |
448 | 472 |
|
449 | 473 | # get the fields to be used during update/insert
|
450 | 474 | insert_fields, update_fields = self._get_upsert_fields(first_row)
|
|
0 commit comments