Introduce a serializer field for GenericForeignKeys #10442

Closed
opened 2025-12-29 21:31:30 +01:00 by adam · 1 comment
Owner

Originally created by @jeremystretch on GitHub (Nov 5, 2024).

Originally assigned to: @bctiemann on GitHub.

Proposed Changes

Devise and implement a custom serializer field to represent GenericForeignKeys on models. This is currently handled using a read-only SerializerMethodField, which requires a boilerplate method be included on the serializer class. For instance, the code below is from the serializer for circuit terminations:

    @extend_schema_field(serializers.JSONField(allow_null=True))
    def get_termination(self, obj):
        if obj.termination_id is None:
            return None
        serializer = get_serializer_for_model(obj.termination)
        context = {'request': self.context['request']}
        return serializer(obj.termination, nested=True, context=context).data

Justification

Introducing a custom field to represent GFK relationships allows us to enforce a standard implementation and reduce boilerplate.

Originally created by @jeremystretch on GitHub (Nov 5, 2024). Originally assigned to: @bctiemann on GitHub. ### Proposed Changes Devise and implement a custom serializer field to represent GenericForeignKeys on models. This is currently handled using a read-only [`SerializerMethodField`](https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield), which requires a boilerplate method be included on the serializer class. For instance, the code below is from the serializer for circuit terminations: ```python @extend_schema_field(serializers.JSONField(allow_null=True)) def get_termination(self, obj): if obj.termination_id is None: return None serializer = get_serializer_for_model(obj.termination) context = {'request': self.context['request']} return serializer(obj.termination, nested=True, context=context).data ``` ### Justification Introducing a custom field to represent GFK relationships allows us to enforce a standard implementation and reduce boilerplate.
adam added the type: housekeepingnetboxstatus: backlog labels 2025-12-29 21:31:30 +01:00
adam closed this issue 2025-12-29 21:31:30 +01:00
Author
Owner

@jeremystretch commented on GitHub (Nov 4, 2025):

As part of this change, we now expose the object_repr field on the /api/core/object-changes/ endpoint.

@jeremystretch commented on GitHub (Nov 4, 2025): As part of this change, we now expose the `object_repr` field on the `/api/core/object-changes/` endpoint.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#10442