[Answered ]-Reverse Relationships in Django-Rest framework

0👍

class BaseSerializer(serializers.ModelSerializer):
    """
    A Base Serializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)
        # Instantiate the superclass normally
        super(BaseSerializer, self).__init__(*args, **kwargs)

        if fields:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)
        if exclude:
            # Drop fields that are specified in the `exclude` argument.
            excluded = set(exclude)
            for field_name in excluded:
                try:
                    self.fields.pop(field_name)
                except KeyError:
                    pass

I used the above class to explicitly exclude the arguments I did not want,

Credit : How to exclude parent when serializer is nested when using Django REST Framework?

2👍

There are a lot of solutions. You can use several types of fields e. g. a StringRelatedField or a SerializerMethodField.

Here is an example with a custom related field:

from rest_framework import serializers


class TrackField(serializers.RelatedField):

    def to_representation(self, value):
        return value.album_name


class TrackSerializer(serializers.ModelSerializer):

    album = TrackField(queryset=Album.objects.all())

    class Meta:
        model = Track
        fields = ('album', 'order', 'title', 'duration')

This produces:

track = Track.objects.get(...)

TrackSerializer(track).data  # Returns {'album': <name of the album>, ...}

Leave a comment