Use primary serializers for nested object relationships #15278
Labels
status: accepted
This issue has been accepted for implementation
type: housekeeping
Changes to the application which do not directly impact the end user
Milestone
Proposed Changes
Following the work completed in #15235, it is no longer necessary to define separate nested serializers to represent related objects. We can instead pass an arbitrary list of fields to include when rendering the serialized object.
For example, the Site serializer currently utilizes nested serializers to display the region to which a site is assigned:
Instead, we can use the primary serializers for each of these related models, passing the specific fields we want the nested representation to include:
Because the desired set of fields typically matches
brief_fields
set on the related serializer'sMeta
class, we can reference it directly. (Passing an arbitrary list of fields where necessary is still possible.)As this approach is a bit verbose, it would be prudent to provide a shortcut in the form of a designated keyword argument when initializing the serializer. For instance, we could pass
nested=True
to imply that only the serializer'sbrief_fields
should be included. (This would be handled under the base serializer class'__init__()
method.)Although this change will obviate the need for many of the current nested serializers, IMO we should retain these in the code base for at least one release cycle, to provide a smooth migration path for plugins which may still utilize them.
Justification
This approach provides two substantial benefits. First, it obviates the need to maintain dedicated nested serializers solely for the purpose of representing related objects. For instance,
NestedManufacturerSerializer
exists only to represent the related manufacturer when viewing a device or module type. With the approach above, it is no longer needed.Second, we can now include arbitrary fields for additional context. For instance, when representing the site to which a rack is assigned, we might want to include its
rack_count
, and when representing a device, instead include itsdevice_count
.It's worth noting that this does not automatically negate the need for all nested serializers. There are at least two scenarios where separate serializers must be defined:
RegionSerializer
cannot be used to represent a region's parent region.DeviceSerialzer
must represent the virtual chassis to which a device is assigned (if any), yetVirtualChassisSerializer
must also represent its master device. A nested serializer must be used in one direction or the other to resolve this circular logic.The text was updated successfully, but these errors were encountered: