Krisnadi
Krisnadi

Reputation: 681

Django Rest Framework optional nested relationship

is it possible to use a nested relation serializer as an option? This is the serializer example from the docs:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = '__all__'

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = '__all__'

when i call the album list localhost:8000/album/1/, this is the response:

{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
        ...
    ],
}

is there any option like this localhost:8000/album/1/?include=tracks, so the tracks data only appear when it stated on the include param.

Upvotes: 2

Views: 630

Answers (2)

Devang Padhiyar
Devang Padhiyar

Reputation: 3697

You can use drf-dynamic-fields package. It is used for dynamic inclusion of fields by passing url paramters as below:

GET /identities

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5,
    "data": "John Doe"
  },
  ...
]

A query with the fields parameter on the other hand returns only a subset of the fields:

GET /identities/?fields=id,data

[
  {
    "id": 1,
    "data": "John Doe"
  },
  ...
]

And a query with the omit parameter excludes specified fields.

GET /identities/?omit=data

[
  {
    "id": 1,
    "url": "http://localhost:8000/api/identities/1/",
    "type": 5
  },
  ...
]

Upvotes: 0

IVNSTN
IVNSTN

Reputation: 9299

An example

class OrderSerializer(ModelSerializer):
    payments = PaymentSerializer(many=True, read_only=True)
    evaluations = OrderEvaluationSerializer(many=True, read_only=True)

    def __init__(self, *args, **kwargs):
        super(OrderSerializer, self).__init__(*args, **kwargs)

        request = kwargs['context']['request']
        include_address = request.GET.get('include_address', False)  # <<<---

        if include_address:  # <<<---
            self.fields['user_location'] = UserLocationSerializer(read_only=True, context=kwargs['context'])  # <<<---

from here: http://masnun.com/2015/10/21/django-rest-framework-dynamic-fields-in-serializers.html

Upvotes: 1

Related Questions