1
votes

I'm using django 1.8 with djangorestframework==3.6.3. I took the model examples from the documentation:

https://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

Here are my serializers:

from rest_framework import serializers
from .models import *

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')


class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration', 'album')

and here is how I call the serializer:

def index(request):
    if Track.objects.all().count() == 0:
        album = Album.objects.create(album_name='something', artist='John')
        Track.objects.create(album=album, order=1, title='something', duration=1)

    print TrackSerializer(instance=Track.objects.all()[0]).data
    return render(request, 'index.html')

The print statement give me: {'duration': 1, 'album': 1, 'order': 1, 'title': u'something'} Why is it not giving me all the field data for the corresponding album?

2

2 Answers

2
votes

In the corresponding example, they've used to return the Album's data whereas you are trying to return/print Track's data.

So, if you try as below, it will print/return the data as described/shown in the DRF doc

def index(request):
    if Track.objects.all().count() == 0:
        album = Album.objects.create(album_name='something', artist='John')

        print(AlbumSerializer(album).data)  # this will print the data as explianed in the doc

        Track.objects.create(album=album, order=1, title='something', duration=1)

    return render(request, 'index.html')

If you want to show the details realted to album, create a new album serializer, AlbumNewSerializer and link it in TrackSerializer as,

class AlbumNewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Album
        fields = ('album_name', 'artist')


class TrackSerializer(serializers.ModelSerializer):
    album = AlbumNewSerializer()

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

NOTE: You could use AlbumSerializer instead of AlbumNewSerializer, but the result maybe in a ugly nested fashion (not tested..)

0
votes

I think you need to do something like this:

class TrackSerializer(serializers.ModelSerializer):
    album = AlbumSerializer(…)

    ...