diff --git a/awx/main/tests/functional/models/test_activity_stream.py b/awx/main/tests/functional/models/test_activity_stream.py index a8e0d4ef87..bdee4b80c1 100644 --- a/awx/main/tests/functional/models/test_activity_stream.py +++ b/awx/main/tests/functional/models/test_activity_stream.py @@ -8,9 +8,18 @@ from awx.main.models import ( Organization, JobTemplate, Credential, - CredentialType + CredentialType, + InventorySource ) +# other AWX +from awx.main.utils import model_to_dict +from awx.api.serializers import InventorySourceSerializer + + +model_serializer_mapping = { + InventorySource: InventorySourceSerializer +} class TestImplicitRolesOmitted: @@ -140,3 +149,11 @@ class TestUserModels: entry = ActivityStream.objects.filter(user=alice)[0] assert entry.operation == 'create' assert json.loads(entry.changes)['password'] == 'hidden' + + +@pytest.mark.django_db +def test_missing_related_on_delete(inventory_source): + old_is = InventorySource.objects.get(name=inventory_source.name) + inventory_source.inventory.delete() + d = model_to_dict(old_is, serializer_mapping=model_serializer_mapping) + assert d['inventory'] == '-{}'.format(old_is.inventory_id) diff --git a/awx/main/utils/common.py b/awx/main/utils/common.py index 473683a668..5aedf8b216 100644 --- a/awx/main/utils/common.py +++ b/awx/main/utils/common.py @@ -21,6 +21,7 @@ import tempfile from decorator import decorator # Django +from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext_lazy as _ from django.db.models.fields.related import ForeignObjectRel, ManyToManyField @@ -288,7 +289,10 @@ def get_allowed_fields(obj, serializer_mapping): def _convert_model_field_for_display(obj, field_name, password_fields=None): # NOTE: Careful modifying the value of field_val, as it could modify # underlying model object field value also. - field_val = getattr(obj, field_name, None) + try: + field_val = getattr(obj, field_name, None) + except ObjectDoesNotExist: + return '-{}'.format(obj._meta.verbose_name, getattr(obj, '{}_id'.format(field_name))) if password_fields is None: password_fields = set(getattr(type(obj), 'PASSWORD_FIELDS', [])) | set(['password']) if field_name in password_fields: