MCPcopy
hub / github.com/django/django / build_instance

Function build_instance

django/core/serializers/base.py:331–354  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

329
330
331def 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
357def deserialize_m2m_values(field, field_value, using, handle_forward_references):

Callers

nothing calls this directly

Calls 6

db_managerMethod · 0.80
ModelClass · 0.50
getMethod · 0.45
natural_keyMethod · 0.45
to_pythonMethod · 0.45
get_by_natural_keyMethod · 0.45

Tested by

no test coverage detected