diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py b/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py index e95dac4890..d417707029 100644 --- a/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py +++ b/cms/djangoapps/contentstore/rest_api/v2/views/downstreams.py @@ -456,25 +456,23 @@ class DownstreamView(DeveloperErrorViewMixin, APIView): """ downstream = _load_accessible_block(request.user, usage_key_string, require_write_access=True) affected_blocks: list[XBlock] = [] + # Get the upstream ref before severing the link, so we can delete + # the corresponding ComponentLink or ContainerLink below. + upstream_ref = downstream.upstream try: - # Try to get the upstream key before severing the link, so we can delete - # the corresponding ComponentLink or ContainerLink below. - try: - upstream_key = UpstreamLink.get_for_block(downstream).upstream_key - except NoUpstream: - # Even if we don't have an UpstreamLink, we still need to check - # if the block has the upstream key set, so we don't want to - # raise an exception here. - upstream_key = None affected_blocks = sever_upstream_link(downstream) # Remove the ComponentLink or ContainerLink, if it exists. - if upstream_key: - if isinstance(upstream_key, LibraryUsageLocatorV2): + if upstream_ref: + try: ComponentLink.get_by_downstream_usage_key(downstream.usage_key).delete() - elif isinstance(upstream_key, LibraryContainerLocator): - ContainerLink.get_by_downstream_usage_key(downstream.usage_key).delete() + except ComponentLink.DoesNotExist: + try: + ContainerLink.get_by_downstream_usage_key(downstream.usage_key).delete() + except ContainerLink.DoesNotExist: + # If neither link exists, that's fine--we just wanted to clean up if possible. + pass except NoUpstream: logger.exception( "Tried to DELETE upstream link of '%s', but it wasn't linked to anything in the first place. "