netbox-community / netbox

The premier source of truth powering network automation. Open source under Apache 2. Try NetBox Cloud free: https://netboxlabs.com/free-netbox-cloud/
http://netboxlabs.com/oss/netbox/
Apache License 2.0
16.16k stars 2.59k forks source link

object-types api - add combined `app_label.model` field for quick lookups #16427

Open ITJamie opened 5 months ago

ITJamie commented 5 months ago

NetBox version

v4.0.3

Feature type

Data model extension

Proposed functionality

Add a read only field to the responses on the object-types API. allow filtering based on this "combined" field too EG:

        {
            "id": 39,
            "url": "https://demo.netbox.dev/api/extras/object-types/39/",
            "display": "DCIM | interface",
            "app_label": "dcim",
            "model": "interface",
            "combined": "dcim.interface" # new field
        },

Use case

other api endpoints sometimes return the combined app_label.model string. to reference other object types. eg on the interfaces API, an assigned interface returns "assigned_object_type": "dcim.interface". however to filter by that assigned_object_type you need to know the object-type id,

    "results": [
        {
            "id": 183,
            "url": "https://demo.netbox.dev/api/ipam/ip-addresses/183/",
            "display": "1.1.1.1/32",
# truncated
            "role": null,
            "assigned_object_type": "dcim.interface",
            "assigned_object_id": 1767,
# truncated
        },

being able to quickly use the combined string (egdcim.interface) to quickly lookup the object-type id without doing any text manipulation would be great

Database changes

N/A

External dependencies

N/A

jeremystretch commented 5 months ago

Add a read only field to the responses on the object-types API. allow filtering based on this "combined" field too

It's worth pointing out that merely adding a read-only field is trivial, but enabling it to be used for filtering is a bit more involved.

Also, Django refers to this as the "natural key" for a content type; we might want to adopt the same name for the serializer field & filter.

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.get_for_model(Site)
<ContentType: DCIM | site>
>>> ContentType.objects.get_for_model(Site).natural_key()
('dcim', 'site')
ITJamie commented 5 months ago

I guess adding it as an actual field to make it easy to filter would make sense. this endpoint is only really used in an informational way.

having it backfill the data into the model as part of migration wouldn't be hard.

as for the fieldname, natural_key would make a lot of sense, as long as it doesn't cause any kind of collision or confusion in the model