Repository: django/django
File: django/core/serializers/base.py (Python)

Code before:


def build_instance(Model, data, db):
    """
    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.
    """
    default_manager = Model._meta.default_manager
    pk = data.get(Model._meta.pk.attname)
    natural_key_method = getattr(Model, "natural_key", None)
    if (
        pk is None
        and hasattr(default_manager, "get_by_natural_key")
        and callable(natural_key_method)
    ):
        obj = Model(**data)
        obj._state.db = db
        natural_key = obj.natural_key()
        if natural_key:
            try:
                existing = default_manager.db_manager(db).get_by_natural_key(
                    *natural_key
                )
                data[Model._meta.pk.attname] = Model._meta.pk.to_python(existing.pk)
            except Model.DoesNotExist:
                pass
    return Model(**data)


def deserialize_m2m_values(field, field_value, using, handle_forward_references):
    model = field.remote_field.model
    if hasattr(model._default_manager, "get_by_natural_key"):

        def m2m_convert(value):
            if hasattr(value, "__iter__") and not isinstance(value, str):
                return (
                    model._default_manager.db_manager(using)
                    .get_by_natural_key(*value)
                    .pk
                )
            else:
                return model._meta.pk.to_python(value)

    else:

        def m2m_convert(v):
            return model._meta.pk.to_python(v)

    try:

Review comment (suggestion):
If we're taking the opportunity to factor this line out, then let's move it out of the `try` and under an `else`.

Code after:
            data[Model._meta.pk.attname] = Model._meta.pk.to_python(
                default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
            )
        except Model.DoesNotExist:
            pass
    return Model(**data)


def deserialize_m2m_values(field, field_value, using, handle_forward_references):
    model = field.remote_field.model
    if hasattr(model._default_manager, "get_by_natural_key"):

        def m2m_convert(value):
            if hasattr(value, "__iter__") and not isinstance(value, str):
                return (
                    model._default_manager.db_manager(using)
                    .get_by_natural_key(*value)
                    .pk
                )
            else:
                return model._meta.pk.to_python(value)

    else:

        def m2m_convert(v):
            return model._meta.pk.to_python(v)

    try:
        pks_iter = iter(field_value)
    except TypeError as e:
        raise M2MDeserializationError(e, field_value)
    try:
        values = []
        for pk in pks_iter:
            values.append(m2m_convert(pk))
        return values
    except Exception as e:
        if isinstance(e, ObjectDoesNotExist) and handle_forward_references:
            return DEFER_FIELD
        else:
            raise M2MDeserializationError(e, pk)


def deserialize_fk_value(field, field_value, using, handle_forward_references):
    if field_value is None:
        return None
    model = field.remote_field.model
    default_manager = model._default_manager
    field_name = field.remote_field.field_name
    if (
        hasattr(default_manager, "get_by_natural_key")