Build a model instance. If the model instance doesn't have a primary key and the model supports natural keys, try to retrieve it from the database.
(Model, data, db)
| 329 | |
| 330 | |
| 331 | def build_instance(Model, data, db): |
| 332 | """ |
| 333 | Build a model instance. |
| 334 | |
| 335 | If the model instance doesn't have a primary key and the model supports |
| 336 | natural keys, try to retrieve it from the database. |
| 337 | """ |
| 338 | default_manager = Model._meta.default_manager |
| 339 | pk = data.get(Model._meta.pk.attname) |
| 340 | if ( |
| 341 | pk is None |
| 342 | and hasattr(default_manager, "get_by_natural_key") |
| 343 | and hasattr(Model, "natural_key") |
| 344 | ): |
| 345 | obj = Model(**data) |
| 346 | obj._state.db = db |
| 347 | natural_key = obj.natural_key() |
| 348 | try: |
| 349 | data[Model._meta.pk.attname] = Model._meta.pk.to_python( |
| 350 | default_manager.db_manager(db).get_by_natural_key(*natural_key).pk |
| 351 | ) |
| 352 | except Model.DoesNotExist: |
| 353 | pass |
| 354 | return Model(**data) |
| 355 | |
| 356 | |
| 357 | def deserialize_m2m_values(field, field_value, using, handle_forward_references): |
nothing calls this directly
no test coverage detected