Fixed #20463 -- Made get_or_create more robust.

When an exception other than IntegrityError was raised, get_or_create
could fail and leave the database connection in an unusable state.

Thanks UloPe for the report.