Search code examples
pythondjangodjango-rest-frameworkrelationalserialization

StringRelatedField does not working as shown in the official tutorial


I went through the "Serializer relations" at https://www.django-rest-framework.org/api-guide/relations/ and got some problems with StringRelatedField relational field. So, in that tutorial they had given the models.py and serializers.py. I added the views.py and the urls.py. My views.py:

# views.py 
from django.shortcuts import render 
from music.models import Album, Track 
from music.serializers import AlbumSerializer  
from rest_framework import generics


    class AlbumList(generics.ListCreateAPIView):
        queryset = Album.objects.all()
        serializer_class = AlbumSerializer


    class AlbumDetail(generics.RetrieveUpdateDestroyAPIView):
        queryset = Album.objects.all()
        serializer_class = AlbumSerializer

My urls.py:

# urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from music import views

urlpatterns = [
    path('music/', views.AlbumList.as_view()),
    path('music/<int:pk>/', views.AlbumDetail.as_view(), name='track-detail'),
]

urlpatterns = format_suffix_patterns(urlpatterns)

Using the python manage.py shell command, I created an album and track object like the following:

>>> from music.models import Album, Track
>>> from music.serializers import AlbumSerializer
>>> album = Album(album_name="Desert", artist="Beduin")
>>> album.save()
>>> track = Track(album=album, order=1, title="Finding Water", duration="2" )
>>> track.save()
>>> track = Track(album=album, order=2, title="My Camel", duration="2" )
>>> track.save()

But when I run the server, then I get this:

{
     ...
        "album_name": "Desert",
        "artist": "Beduin",
        "tracks": [
            "Track object (2)",
            "Track object (3)"
        ]
    ...
}

I thought that the StringRelatedField uses the unicode method to show the object representation. But in my case, it says "Track object (2)" and "Track object (3)" instead of the number and title of the track. Can somebody help? NOTE: the models.py and serializers.py I use are exactly the same as in the tutorial.


Solution

  • To solve this problem you can just add a __str__ method to your model, like this:

    def __str__(self):
        return f'{self.number}: {self.title}'