networktocode / ntc-netbox-plugin-onboarding

A plugin for NetBox to easily onboard new devices.
Other
246 stars 46 forks source link

Changes for multiple criteria searching #98

Closed carbonarok closed 3 years ago

carbonarok commented 3 years ago

Draft new function has been created to search multiple criteria for a single model. If the search strategy is set to loose, the function will search in a loop for each criteria.

Search criteria is pushed into the function, in a nested dictionary. The first item in the array should be the primary search. Example below:

def object_match(obj, search_array):
    """Used to search models for multiple criteria."""
    try:
        result = obj.objects.get(**search_array[0])
        return result
    except obj.DoesNotExist as error:
        if PLUGIN_SETTINGS['object_match_strategy'] == "loose":
            for search_array_element in search_array[1:]:
                try:
                    result = obj.objects.get(**search_array_element)
                    return result
                except obj.DoesNotExist:
                    pass
                except obj.Multiple:
                    raise OnboardException(reason="fail-general", message=f"ERROR multiple objects found")
        raise

search_array = [
      {"slug": nb_device_type_slug},
      {"slug__iexact": nb_device_type_slug},
      {"model__iexact": netdev_model},
      {"part_number__iexact": netdev_model}
]
nb_device_type = object_match(DeviceType, search_array)
mzbroch commented 3 years ago

@carbonarok Can you please also update the docs as a part of this PR as it introduces new options?

mzbroch commented 3 years ago

Replaced by #99